美文网首页
Rust—变量特性

Rust—变量特性

作者: Sivin | 来源:发表于2019-11-07 13:25 被阅读0次

    变量(variables)

    • 变量的声明必须以let关键字修饰
    • 变量的值默认是不可以被改变的
    • 如果想要变量改变其值,则必须加上mut关键字修饰
     let x  = 5; 
     x = 6; //编译失败,变量的值默认是不可以被改变的
     let mut y = 6;
     y = 7; //正确
    

    常量(Constants)

    • 使用const关键字修饰,而不是let
    • 值永远不能被改变,不允许使用mut对常量进行修饰
    • 定义时必须注明值的类型
    • 常量可以在任何作用域中声明,包括全局作用域
    • 常量只能被设置成常量表达式,不能是函数调用的结果,或者其他任何只能在运行时计算出的值
    • 常量在整个程序生命周期中都有效
    const MAX_VALUE : u32 = 100_00;
    

    隐藏(Shadowing)

    我们可以定义一个与之前变量同名的新变量,而新变量会隐藏之前的变量。

    fn main(){
        let x = 7;
        println!("the value of x = {}",x);
        let x = x+8;
        println!("the value of x = {}",x);
        let x = x * 9;
        println!("the value of x = {}",x);
    }
    ---结果---
    the value of x = 7
    the value of x = 15
    the value of x = 135
    

    隐藏与变量被标记为mut是有区别的,当我们不小心对变量进行重新赋值时,如果没有使用let关键字,将会得到一个编译错误。通过使用 let,我们可以用这个值进行一些计算,不过计算完之后变量仍然是不变的。

    隐藏于mut的另一个区别,当再次使用let时,实际上是创建了一个新变量,我们可以改变值的类型,但复用这个名字。

    fn main(){
        let x = 7;
        println!("the value of x = {}",x);
        let x = 8.1;
        println!("the value of x = {}",x);
        let x = "str";
        println!("the value of x = {}",x);
    }
    ---结果---
    the value of x = 7
    the value of x = 8.1
    the value of x = str
    

    相关文章

      网友评论

          本文标题:Rust—变量特性

          本文链接:https://www.haomeiwen.com/subject/ygtvbctx.html