← 返回课程: Rust from scratch

Variables, mutability, constants and shadowing

视频即将上线

In almost every language a variable can change whenever you want. Rust takes the opposite decision: by default, a variable is immutable. Once you give it a value with let, you cannot reassign it. This is not a whim: knowing that a value does not change makes code easier to reason about and avoids a whole family of bugs, especially when several parts of the program (or several threads) share data.

let and let mut

To allow changes you must ask for it explicitly with mut. That way, whoever reads the code sees right away which variables can change. Try this program: the first variable is never modified, the second one is. If you tried x = 6 on the immutable one, the compiler would answer with the error 'cannot assign twice to immutable variable'. That is the sign you should add mut, or better, ask yourself whether you really need to change the value.

rust
fn main() {
    let x = 5;          // immutable
    let mut y = 10;     // mutable
    println!("x = {x}, y = {y}");

    y = y + 1;          // allowed because of mut
    y += 4;             // shorthand: y = y + 4
    println!("y is now {y}");
}
rust
fn main() {
    let x = 5;
    x = 6; // ERROR: cannot assign twice to immutable variable
    println!("{x}");
}

Constants

A constant is declared with const, always requires the type, and its value must be computable at compile time. Unlike let, it is never mutable and it can be declared outside any function, at global level. By convention it is written in UPPERCASE with underscores. Use them for fixed values in your program: the maximum number of attempts, a conversion factor, the application name.

rust
const SECONDS_PER_HOUR: u32 = 60 * 60;
const APP_NAME: &str = "Timer";

fn main() {
    let hours = 3;
    println!("{APP_NAME}: {hours} h = {} s", hours * SECONDS_PER_HOUR);
}

Shadowing: reusing a name

You can declare another variable with the same name by using let again. The new one shadows the old one: from that point on, the name refers to the new value. It is different from mut: here you create a new variable, so you can even change its type. It is very useful for transforming data step by step, for example converting text with spaces into a number, without inventing names like clean_text and final_number.

rust
fn main() {
    let spaces = "   ";          // a &str
    let spaces = spaces.len();   // now a usize: shadowing changes the type
    println!("{spaces} spaces");

    let x = 5;
    let x = x + 1;
    {
        let x = x * 2;           // inner scope shadows only inside the braces
        println!("inner x = {x}");
    }
    println!("outer x = {x}");
}

With mut you could not do what the example does: if spaces were mut, you could not assign a number to a variable that holds text, because a variable's type cannot change. Practical rule: use shadowing when you transform a value and no longer need the original; use mut when the value really changes over time (a counter, an accumulator).

A note about types: you usually do not need to write them, because the compiler infers them from the value. When you want to state them, use a colon: let age: u8 = 30. It is mandatory, for example, when converting text to a number, because the compiler cannot guess which numeric type you mean. We will see that in the next lesson.

检验所学

第 1 / 1

What happens if you assign twice to a variable declared with let (without mut)?

✎ 我的笔记

仅保存在此浏览器中。登录后可保存到账号。0/5000 字符

← 上一节下一节 →