变量:默认是不可修改的

let用于声明变量,修改变量会导致编译会报错

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

mut声明x为可修改的:

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

话说rust的编译报错的错误提示还是蛮好看的:

% cargo build
   Compiling variables v0.1.0
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` (bin "variables") due to 1 previous error

类型

  • 比较常规的: i8、u32、u128。
  • 0x8c 16进制、0o77 8禁止、0b1111_0000 2进制、b’A’ byte(u8)。
  • 可以用_来让数值更容易读,例如: 1000_0000,等同于1000000
  • 元组可用用tule.0, tup.2来访问成员。
  • 数组
    • let a: [i32; 5] = [1, 2, 3, 4, 5];
    • let a = [3; 5]; 等同于 let a = [3, 3, 3, 3, 3];

函数

  • 区分expression和statement。expression会返回值,statement不返回。
  • 函数最后要返回结果需要使用expression(写法上不带分号)

控制流

  • 循环中break后可以带语句返回值
  • loop {}
  • for a < 100 {}
  • for item in iterms {}
  • for number in 1..4 {} 循环三次