变量和可变性

变量和可变性

当一个变量是不可变的,一旦一个值被绑定到一个名字上,你就不能改变那个值。 为了说明这一点,让我们在项目目录中生成一个名为variables的新项目,使用.cargo new variables

然后,在您的新变量目录中,打开src/main.rs并将其代码替换为以下代码。这段代码还不能编译,我们将首先检查不变性错误。

文件名:src/main.rs

fn main() {
    let x = 5;
    println!("The value of x is: {}", x);
    x = 6;
    println!("The value of x is: {}", x);
}

使用 保存并运行程序cargo run。您应该会收到一条错误消息,如以下输出所示:

 cargo run
   Compiling variables v0.1.0 (file:///projects/variables)
error[E0384]: cannot assign twice to immutable variable `x`
 --> src/main.rs:4:5
  |
2 |     let x = 5;
  |         -
  |         |
  |         first assignment to `x`
  |         help: consider making this binding mutable: `mut x`
3 |     println!("The value of x is: {}", x);
4 |     x = 6;
  |     ^^^^^ cannot assign twice to immutable variable

For more information about this error, try `rustc --explain E0384`.
error: could not compile `variables` due to previous error

错误消息表明错误的原因是您cannot assign twice to immutable variable x,因为您尝试为不可变x变量分配第二个值。

当我们尝试更改指定为不可变的值时,我们会遇到编译时错误,这一点很重要,因为这种情况可能会导致错误。如果我们的代码的一部分假设一个值永远不会改变,而我们的另一部分代码改变了这个值,那么代码的第一部分可能不会按照它的设计来做。这种错误的原因在事后很难追查,尤其是当第二段代码只是偶尔改变值时但是可变性可能非常有用,并且可以使代码更方便编写。变量仅在默认情况下是不可变的;您可以通过mut在变量名前面添加来使它们可变。添加mut还通过指示代码的其他部分将更改此变量的值来向代码的未来读者传达意图。

fn main() {
    let mut x = 5;
    println!("The value of x is: {}", x);
    x = 6;
    println!("The value of x is: {}", x);
}

当我们现在运行程序时,我们得到:

$ cargo run
   Compiling variables v0.1.0 (file:///projects/variables)
    Finished dev [unoptimized + debuginfo] target(s) in 0.30s
     Running `target/debug/variables`
The value of x is: 5
The value of x is: 6

常数


#![allow(unused)]
fn main() {
const THREE_HOURS_IN_SECONDS: u32 = 60 * 60 * 3;
}

Shadowing

    let x = 5;

    let x = x + 1;

    {
        let x = x * 2;
        println!("The value of x in the inner scope is: {}", x);
    }

    println!("The value of x is: {}", x);
}


fn main() {
    let mut spaces = "   ";
    spaces = spaces.len();
}

全部评论

相关推荐

10-29 15:51
嘉应学院 Java
后端转测开第一人:你把简历的学历改成北京交通大学 去海投1000份发现基本还是没面试
点赞 评论 收藏
分享
淬月星辉:专利是什么?至少描述一下吧,然后把什么计算机二级、普通话这种拉低格调的证书删掉,不然hr以为你没东西写
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务