声明变量 let x = 5; 默认为不可变变量,以下这个写法会出现编译错误
fn main() {
let x = 5;
println!("the value of x is {}", x);
x = 6;
println!("the value of x is {}", x);
}
可变变量需要加上 mut 前缀
fn main() {
let mut x = 5;
println!("the value of x is {}", x);
x = 6;
println!("the value of x is {}", x);
}
variable 也可以是一个expression
fn hello() {
let x = {
let y = 1;
y + 1
}
println!("the value of x is {}", x)
}
注意第4行末尾没有; 这表示这是一个expression,而不是一个statement
const
const 一定是不可变得,以全部大写和下划线命名,const必须声明变量类型,例如
const MAX_NUMBER: u32 = 100
tuple
tuple 可以通过patten match来取出变量,这个叫做destructuring,或者通过index来访问变量
fn main() {
let tup:(i32, f64, u8) = (10, 6.4, 1);
let (x, y, z) = tup;
println!("the value of y is {}", y);
println!("value is {}", tup.2);
}
heap
fn main() {
let x = 5; // on the stack
let y = Box::new(5); // on the heap
}