rust所有变量默认是不可变的
声明增加 mut 才可以改变
rust 数据类型
rust是静态类型语言
Scalar Types
-
integer
Length Signed Unsigned 8 i8 u8 16 i16 u16 32 i32 u32 64 i64 u64 128 i128 u128 arch isize usize iszie和usize取决于电脑架构 int 默认是i32声明示例
literals 示例 Decimal 1_000 Hex 0xff Octal 0o77 Binary 0b1111_0000 Byte(u8 only) b'A' 标准库中处理溢出的方法
wrapping_*循环checked_*溢出返回Noneoverflowing_*返回数字值和是否溢出saturating_*返回最接近的值
-
floating-point
- f32
- f64 默认
let x = 2.0 //f64
-
boolean 1 byte长度 使用
bool -
character 4 byte长度 使用
char#![allow(unused)] fn main() { let z: char = 'ℤ'; // with explicit type annotation let heart_eyed_cat = '😻'; }
Compound Types
-
tuple 固定长度,声明后长度不能变动 两种使用方式 1 destructuring
fn main() { let tup = (500, 6.4, 1); let (x, y, z) = tup; println!("The value of y is: {y}"); }2 indexing
fn main() { let x: (i32, f64, u8) = (500, 6.4, 1); let five_hundred = x.0; let six_point_four = x.1; let one = x.2; }空元组
()叫unit,表示一个空值或者一个空的返回类型,表达式在返回空值时隐式返回unit -
array 固定长度,分配在栈上
#![allow(unused)] fn main() { let months = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"]; }声明时指定类型和长度
#![allow(unused)] fn main() { let a: [i32; 5] = [1, 2, 3, 4, 5]; }指定相同内容和长度
#![allow(unused)] fn main() { let a = [3; 5]; //a = [3, 3, 3, 3, 3] }