跳转到主要内容
模块 1 · 第 1 课(共 2)课程中的1/14~10 min
模块课程(1/2)

变量和可变性

在 Rust 中,变量和内存管理遵循两个基本原则:安全和控制。因此,与许多其他编程语言不同,Rust 中的变量默认是不可变的。

这意味着一旦将值分配给变量,就无法更改。如果您尝试修改它,编译器将引发错误。

不可变变量和 mut 关键字

要声明变量,我们使用 let 关键字:

Rust
let x = 5; // Immutable by default
// x = 6; // ERROR! The compiler will refuse to build this code.

如果需要修改变量的值,则必须在 let 之后使用 mut 关键字显式使其可变:

Rust
let mut y = 10; // Mutable
println!("Il valore di y e: {}", y);
y = 15; // Valid!
println!("Il valore modificato di y e: {}", y);

使用 mut 前缀可以清楚地向编译器和任何读取代码的人传达该值将在执行期间发生变化的信息。

影子

Rust 还允许 shadowing 的概念,即再次使用 let 关键字重新声明具有相同名称的变量。新变量“隐藏”(或覆盖)前一个变量:

Rust
let x = 5;
let x = x + 1; // Shadowing: x is now 6
let x = x * 2; // Shadowing: x is now 12

与 mut 不同,阴影允许您:

  1. 更改变量的数据类型,同时保持相同的名称。
  2. 变换后保持变量的不变性。
Rust
let spaces = "   "; // Type: &str (string)
let spaces = spaces.len(); // Type: usize (number)

阴影和范围的用处

阴影不限于同一个块;它可以在嵌套块 ({}) 中使用来临时覆盖某个值。当内部块结束时,原始变量再次变得可见:

Rust
let x = 5;
{
    let x = x * 2; // Shadowing valid only inside the block
    println!("Value in the inner block: {}", x); // Prints 10
}
println!("Value in the outer block: {}", x); // Prints 5

这种机制非常安全和高效,因为它完全发生在编译时,确保类型安全,而不会产生任何运行时性能开销。


自己尝试一下

锻炼#rust.m1.l1.e1
尝试:0加载中...

声明一个名为 x 的可变变量,初始值为 5。接下来,将 x 加 10 并使用 println! 将其打印到屏幕上。宏。

正在加载编辑器...
显示提示

使用“let mut x = 5;”声明变量,然后使用“x += 10;”(或“x = x + 10;”)递增它,最后使用“println!('{}', x);”打印它。

3 次尝试后可用的解决方案

锻炼#rust.m1.l1.e2
尝试:0加载中...

声明一个值为 10 的不可变变量 y。通过使用 let 再次声明它以将其先前值乘以 2 来隐藏 y,最后使用 println! 打印它。

正在加载编辑器...
显示提示

Use `let y = 10;`, then shadow it by declaring it again with `let y = y * 2;` and finally use `println!` to display it.

3 次尝试后可用的解决方案

锻炼#rust.m1.l1.e3
尝试:0加载中...

Declare an immutable variable named input containing the string value "42". Shadow input by declaring it as an integer of type i32, converting the original value via input.parse::<i32>().unwrap(). Finally, print it using the println! macro.

正在加载编辑器...
显示提示

Declare `let input = "42";`, then shadow it with `let input: i32 = input.parse().unwrap();` and print it using `println!("{}", input);`.

3 次尝试后可用的解决方案