Variables and Mutability(变量和可变性)
- 变量声明有三种:不变量(运行期的常量),变量以及(编译期的)常量。
- 变量可以重复绑定,后声明的变量覆盖前面声明的同名变量,重复绑定时可改变类型。
// 运行期常量(不可变变量 immutable variable)
let x = 5;
x = 6; // compile error
// 变量(可变变量 mutable variable)
let mut x = 5;
x = 6;
// 编译期常量(constant)
const MAX_POINTS: u32 = 100_000;
// 重复绑定(不改变类型)
let x = 5;
let x = x + 1;
let x = x * 2;
// 重复绑定(改变类型)
let spaces = " ";
let spaces = spaces.len();
Data Types(数据类型)
- Scalar Types(标量类型)
- Integer Types(整形)
- i8, u8, i16, u16, i32, u32, i64, u64
- Decimal, Hex, Octal, Binary, Byte
- Floating-Point Types(浮点类型)
- Boolean Type(布尔类型)
- Character Type(字符类型)
- Compound Types(复合类型)
// 元组(带类型声明 type annotation)
let tup: (i32, f64, u8) = (500, 6.4, 1);
// 元组(类型自动推导,解构 destructuring)
let tup = (500, 6.4, 1);
let (x, y, z) = tup;
println!("The value of y is: {}", y);
// 元组(使用下标)
let x: (i32, f64, u8) = (500, 6.4, 1);
let five_hundred = x.0;
let six_point_four = x.1;
let one = x.2;