Rust 运算符

算术、比较、逻辑、位运算,以及 Rust 特有的溢出行为。

Beginner
Key Pointsdebug 构建整数溢出会 panic,release 构建会环绕——这个差别必须知道。

算术

Rust
fn main() {
    let a = 7;
    let b = 3;

    println!("{} {} {} {} {}", a + b, a - b, a * b, a / b, a % b);
    println!("{}", 7.0 / 3.0);
}
Output
10 4 21 2 1
2.3333333333333335

Integer division truncates toward zero: 7/3 == 2. Rust has no implicit numeric conversion — 1 + 1.0 fails to compile; write 1 as f64 + 1.0.

溢出

Rust
fn main() {
    let x: u8 = 255;
    // let y = x + 1;         // debug: panic 'attempt to add with overflow'
                              // release: 环绕成 0

    println!("{}", x.wrapping_add(1));    // 0,总是环绕
    println!("{}", x.checked_add(1).is_none());  // true
    println!("{}", x.saturating_add(1));  // 255,饱和
    println!("{}", x.overflowing_add(1).0); // 0
}
Output
0
true
255
0
MethodBehaviour
wrapping_add环绕,不 panic
checked_add返回 Option,溢出为 None
saturating_add饱和到最大/最小值
overflowing_add返回 (值, 是否溢出)
"Panics in debug, wraps silently in release" is a dangerous inconsistency. For money, counters and length math, **use checked_* explicitly** rather than relying on the profile.

比较与逻辑

Rust
fn main() {
    println!("{} {} {}", 1 == 1, 1 != 2, 3 > 2);
    println!("{} {} {}", true && false, true || false, !true);

    // 短路求值
    let v: Option<i32> = None;
    if v.is_some() && v.unwrap() > 0 {
        println!("正数");
    } else {
        println!("没有值或不是正数");
    }
}
Output
true true true
false true false
没有值或不是正数

位运算

Rust
fn main() {
    let a = 0b1100;    // 12
    let b = 0b1010;    // 10

    println!("{:04b} {:04b} {:04b} {:04b}", a & b, a | b, a ^ b, !a & 0b1111);
    println!("{} {}", a << 1, a >> 2);
}
Output
1000 1110 0110 0011
24 3

Rust's ! is both logical NOT and bitwise complement, disambiguated by type. ^ is XOR only — there is no power operator; use i32::pow or f64::powi.

复合赋值与优先级

Rust
fn main() {
    let mut x = 10;
    x += 5;  println!("{}", x);
    x -= 3;  println!("{}", x);
    x *= 2;  println!("{}", x);
    x /= 4;  println!("{}", x);
    x %= 4;  println!("{}", x);
    x <<= 2; println!("{}", x);
    x |= 1;  println!("{}", x);
}
Output
15
12
24
6
2
8
9

Rust has no ++ or --; use x += 1. Precedence follows C: unary > * / % > + - > shifts > & > ^ > | > comparisons > && > ||.

Friends & Partners