变量与基本类型

2026-11-28 · Rust · Rust入门

实验环境:rustc / cargo 1.93(Linux),文中代码、报错与输出均为实测。

上一篇把工具链装好了,这篇讲声明变量和 Rust 的基本类型。

变量

let 绑定的值默认不可变。想改就得显式声明 mut:

fn main() {
    let mut a = 0;
    a = 5;              // OK,a 是 mutable 的
    println!("{a}");
}

如果忘了 mut,编译器会直接拦下来(这是它帮你少写 bug 的方式之一):

$ rustc main.rs
error[E0384]: cannot assign twice to immutable variable `x`
 --> main.rs:1:41
  |
1 | fn main() { let x = 5; println!("{x}"); x = 6; }
  |             - first assignment to `x` ^^^^^ cannot assign twice to immutable variable
help: consider making this binding mutable

影子变量(shadowing)和改值不是一回事:重新用同一个名字 let 一次,是新建了一个变量、把旧的盖住,而不是在改原来的。它俩的区别在于——影子变量可以换类型:

fn main() {
    let x = 5;
    let x = x + 1;              // 新的 x = 6,还是整数
    let spaces = "   ";         // 先是字符串
    let spaces = spaces.len();  // 影子变量把它变成整数 3
    println!("x={x} spaces={spaces}");
}
// x=6 spaces=3

mut 只能在原类型上改值;影子变量可以彻底换个类型。常量用 const,全大写、编译期就定下来、不能用 mut:

const MAX_POINTS: i32 = 100;

标量类型

Rust 是静态类型语言,编译器一般能从值和用法推断出类型;推不出来时要手动标注,比如 let x: i32 = 5;。

整数。分有符号(i8/i16/i32/i64/i128)和无符号(u8/u16/u32/u64/u128),外加跟机器位数走的 isize / usize(数组下标、取长度常用 usize)。不指定大小的时候默认是 i32。

整数运算不会像 C 那样静默溢出给你个错的数:能算出来的溢出,编译期就直接报错——

let x: u8 = 255;
println!("{}", x + 1);   // 编译错误:this arithmetic operation will overflow
// attempt to compute `u8::MAX + 1_u8`, which would overflow

只有运行期才知道的值才轮到运行时处理(debug 构建 panic,release 构建回绕)。

浮点数。f32 / f64,默认 f64:

let pi = 3.14;           // 推断为 f64

布尔 bool,只有 true 和 false。

字符 char 是单引号里一个 Unicode 标量值(占 4 字节),所以 '山' 这样写没问题:

let c: char = '山';
println!("{c}");         // 山

复合类型

元组(tuple)是定长的一串值,可以混不同种类的类型,按下标取(从 .0 开始):

fn main() {
    let t = (1, "two", 3.0);      // (i32, &str, f64)
    println!("first={} second={}", t.0, t.1);   // first=1 second=two
}

元组也能拆开赋值(解构):let (x, y) = (10, 20);。

数组(array)是 [类型; 长度],定长、每个元素同一种类型,连续存在栈上:

fn main() {
    let arr = [10, 20, 30];       // [i32; 3]
    println!("len={} first={}", arr.len(), arr[0]);   // len=3 first=10
}

arr[i] 按下标取,.len() 拿长度。下标越界不会像 C 那样悄悄读到乱数据:写死的越界(比如上面数组直接 arr[5])编译期就报 index out of bounds: the length is 3 but the index is 5;运行期才确定的下标越界则会在 debug 构建里 panic。

下一篇讲函数和控制流。

© 2026 michaelfu'site 原创文章,转载请注明出处:https://michaelfu.site/posts/2026-11-28-rust-vars-types.html

← 返回首页