声明变量 let x = 5; 默认为不可变变量,以下这个写法会出现编译错误

  1. fn main() {
  2. let x = 5;
  3. println!("the value of x is {}", x);
  4. x = 6;
  5. println!("the value of x is {}", x);
  6. }

可变变量需要加上 mut 前缀

  1. fn main() {
  2. let mut x = 5;
  3. println!("the value of x is {}", x);
  4. x = 6;
  5. println!("the value of x is {}", x);
  6. }

variable 也可以是一个expression

  1. fn hello() {
  2. let x = {
  3. let y = 1;
  4. y + 1
  5. }
  6. println!("the value of x is {}", x)
  7. }

注意第4行末尾没有; 这表示这是一个expression,而不是一个statement

const

const 一定是不可变得,以全部大写和下划线命名,const必须声明变量类型,例如

  1. const MAX_NUMBER: u32 = 100

tuple

tuple 可以通过patten match来取出变量,这个叫做destructuring,或者通过index来访问变量

  1. fn main() {
  2. let tup:(i32, f64, u8) = (10, 6.4, 1);
  3. let (x, y, z) = tup;
  4. println!("the value of y is {}", y);
  5. println!("value is {}", tup.2);
  6. }

heap

  1. fn main() {
  2. let x = 5; // on the stack
  3. let y = Box::new(5); // on the heap
  4. }