Rust 运算符
全面讲解 Rust 算术运算与 pow/powf 乘方、关系比较、逻辑短路、补码位运算、赋值与复合赋值以及范围/转型/错误传播/引用解引用运算符,并逐项离线校验。
学完这一章,你能够
- 全面讲解 Rust 算术运算与 pow/powf 乘方、关系比较、逻辑短路、补码位运算、赋值与复合赋值以及范围/转型/错误传播/引用解引用运算符,并逐项离线校验。
算术运算符与显式乘方方法
运算符贯穿 Rust 数值计算、条件判断、位操作与引用处理。基本算术运算符包括加 `+`、减 `-`、乘 `*`、除 `/` 与取余 `%`;需特别注意整数除法向零截断(例如 `5 / 2` 得 `2`、`10 / 3` 得 `3`、`-5 / 2` 得 `-2`),对 `a = 10, b = 3` 依次计算得到和 `13`、差 `7`、积 `30`、商 `3`、余 `1`。
Rust 没有 `**` 乘方运算符,符号 `^` 也仅表示按位异或而非乘方。进行乘方计算须调用标准库方法:整数类型调用 `.pow(exp: u32)`(如 `2_i32.pow(3)` 得 `8`),浮点类型调用 `.powf(exp: f64)`(如 `2.0_f64.powf(2.5)` 得 `5.656854249492381`)或 `.powi(i32)`。本站离线脚本已核对全部算术与乘方结果。
关系比较与布尔逻辑运算符
关系比较运算符包含等于 `==`、不等于 `!=`、大于 `>`、小于 `<`、大于等于 `>=` 与小于等于 `<=`,运算要求左右操作数类型一致且返回 `bool`。对 `x = 5, y = 10` 求值依次得到 `false`、`true`、`false`、`true`、`false`、`true`。
布尔逻辑运算符提供短路与 `&&`、短路或 `||` 以及逻辑非 `!`。对 `a = true, b = false` 计算得 `a && b = false`、`a || b = true`、`!a = false`。离线脚本同时验证了 `&&` 与 `||` 的短路求值特性不会执行未必要的右侧表达式。
位运算符与赋值、复合赋值运算符
位运算符作用于整数二进制位:按位与 `&`、按位或 `|`、按位异或 `^`、按位取反 `!`(注意 Rust 使用 `!` 而非 C 语言的 `~` 进行按位取反)、左移 `<<` 与右移 `>>`。有符号 `i32` 下 `!5` 按二进制补码取反得 `-6`;对无符号 `u8` 的 `x = 0b1010`(10)与 `y = 0b1100`(12),二进制输出依次为 `x & y = 1000`、`x | y = 1110`、`x ^ y = 110`、`!x = 11110101`、`x << 1 = 10100` 与 `x >> 1 = 101`。
赋值与复合赋值运算符包括基本赋值 `=`、算术复合赋值 `+=`/`-=`/`*=`/`/=`/`%=` 以及位运算复合赋值 `&=`/`|=`/`^=`/`<<=`/`>>=`,均要求左值变量已声明为 `mut`。追踪 `let mut n = 5;` 依次执行 `n += 3`(得 `8`)、`n *= 2`(得 `16`)与 `n >>= 1`(得 `8`),离线脚本逐一核验通过。
范围、类型转换、错误传播与引用运算符
Rust 还提供若干高表达力的专用运算符:半开范围 `..`(`1..4` 产生 `1, 2, 3`)与闭区间范围 `..=`(`1..=3` 产生 `1, 2, 3`);显式基础类型转换 `as`(如 `5 as f64`);用于 `Result`/`Option` 提前返回错误的传播算符 `?`;以及内存访问相关的取引用 `&`、解引用 `*`(如 `let b = &a; *b == 10`)和模式绑定引用关键字 `ref`(`let ref y = x;`)。本站离线脚本对以上运算符逐项完成了语义验证。
Rust 算术运算符速查
| 运算符 | 说明 | 示例 | 结果 |
| + | 加法运算 | 5 + 2 | 7 |
| - | 减法运算 | 5 - 2 | 3 |
| * | 乘法运算 | 5 * 2 | 10 |
| / | 除法(整型向零截断整除) | 5 / 2 | 2(整数) |
| % | 取余运算(余数符号同被除数) | 5 % 2 | 1 |
Rust 关系(比较)运算符速查
| 运算符 | 说明 | 示例 | 结果 |
| == | 判断是否相等 | 5 == 5 | true |
| != | 判断是否不等 | 5 != 2 | true |
| > | 判断是否大于 | 5 > 2 | true |
| < | 判断是否小于 | 5 < 2 | false |
| >= | 判断是否大于等于 | 5 >= 5 | true |
| <= | 判断是否小于等于 | 2 <= 5 | true |
Rust 逻辑运算符速查
| 运算符 | 说明 | 示例 | 结果 |
| && | 短路逻辑与(AND) | true && false | false |
| || | 短路逻辑或(OR) | true || false | true |
| ! | 布尔逻辑非(NOT) | !true | false |
Rust 位运算符速查
| 运算符 | 说明 | 示例 | 结果 |
| & | 按位与 | 5 & 3 | 1 |
| | | 按位或 | 5 | 3 | 7 |
| ^ | 按位异或(非乘方) | 5 ^ 3 | 6 |
| ! | 按位取反(有符号整数按补码) | !5 | -6 |
| << | 按位左移 | 5 << 1 | 10 |
| >> | 按位右移 | 5 >> 1 | 2 |
Rust 赋值与复合赋值运算符速查
| 运算符 | 说明 | 示例 | 等价语义 |
| = | 基本赋值(要求变量 mut) | let mut x = 5; x = 3; | x 更新为 3 |
| += | 加并赋值 | x += 2 | x = x + 2 |
| -= | 减并赋值 | x -= 2 | x = x - 2 |
| *= | 乘并赋值 | x *= 2 | x = x * 2 |
| /= | 除并赋值 | x /= 2 | x = x / 2 |
| %= | 取余并赋值 | x %= 2 | x = x % 2 |
| &= |= ^= <<= >>= | 位运算复合赋值 | x &= 2 | 对应按位运算后写回 x |
Rust 范围、转型、传播与引用运算符速查
| 运算符 | 说明 | 示例 |
| .. | 半开范围(不含右边界) | 0..5 产生 0, 1, 2, 3, 4 |
| ..= | 闭合范围(含右边界) | 0..=5 产生 0, 1, 2, 3, 4, 5 |
| as | 显式基础类型转换 | 5 as f32 |
| ? | Result / Option 错误传播提前返回 | some()?; |
| * | 解引用获取指向的值 | *ptr |
| & | 获取变量的不可变引用 | &x |
| ref | 在模式匹配或 let 中绑定为引用 | let ref y = x; |
离线校验 Rust 六大类运算符、向零整除、补码按位取反与 ? / 范围语义
展开查看收起
"""Offline Rust semantic verification lab for Chapter 07 (operators)."""
import json
import math
import shutil
VERSION = "CPython 3.12.14 offline Rust semantic verifier (rustc absent)"
def rust_trunc_div(a: int, b: int) -> int:
# Rust integer division truncates toward zero
q = abs(a) // abs(b)
return -q if (a < 0) ^ (b < 0) else q
def rust_trunc_rem(a: int, b: int) -> int:
return a - rust_trunc_div(a, b) * b
def case_arithmetic_and_pow_ops():
a, b = 10, 3
expected = {
"sample_5_2": {"add": 7, "sub": 3, "mul": 10, "div": 2, "rem": 1},
"sample_10_3": {"add": 13, "sub": 7, "mul": 30, "div": 3, "rem": 1},
"neg_trunc_div": -2,
"neg_trunc_rem": -1,
"int_pow": 8,
"float_powf": round(math.pow(2.0, 2.5), 12),
"rustc_installed": False,
}
actual = {
"sample_5_2": {"add": 5 + 2, "sub": 5 - 2, "mul": 5 * 2, "div": rust_trunc_div(5, 2), "rem": rust_trunc_rem(5, 2)},
"sample_10_3": {"add": a + b, "sub": a - b, "mul": a * b, "div": rust_trunc_div(a, b), "rem": rust_trunc_rem(a, b)},
"neg_trunc_div": rust_trunc_div(-5, 2),
"neg_trunc_rem": rust_trunc_rem(-5, 2),
"int_pow": 2**3,
"float_powf": round(2.0**2.5, 12),
"rustc_installed": shutil.which("rustc") is not None,
}
return {
"name": "arithmetic_and_pow_ops",
"summary": "验证算术五则运算、向零截断整除与取余以及 pow/powf 乘方(区分 ^ 按位异或)",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def case_relational_comparison_ops():
x, y = 5, 10
expected = {
"table_checks": [True, True, True, False, True, True],
"x5_y10": [False, True, False, True, False, True],
}
actual = {
"table_checks": [5 == 5, 5 != 2, 5 > 2, 5 < 2, 5 >= 5, 2 <= 5],
"x5_y10": [x == y, x != y, x > y, x < y, x >= y, x <= y],
}
return {
"name": "relational_comparison_ops",
"summary": "验证六种关系比较运算符 ==、!=、>、<、>=、<= 的布尔返回结果",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def case_logical_short_circuit_ops():
rhs_calls = []
def rhs(val: bool) -> bool:
rhs_calls.append(val)
return val
and_short = False and rhs(True)
or_short = True or rhs(False)
a, b = True, False
expected = {
"a_and_b": False,
"a_or_b": True,
"not_a": False,
"short_circuit_skipped_rhs": True,
}
actual = {
"a_and_b": a and b,
"a_or_b": a or b,
"not_a": not a,
"short_circuit_skipped_rhs": (not and_short) and or_short and (len(rhs_calls) == 0),
}
return {
"name": "logical_short_circuit_ops",
"summary": "验证 &&、||、! 真值表以及逻辑与/逻辑或短路求值不触发右侧副作用",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def case_bitwise_twos_complement_ops():
# Signed i32: !5 == ~5 == -6
signed_ops = {
"and": 5 & 3,
"or": 5 | 3,
"xor": 5 ^ 3,
"not_i32": ~5,
"shl": 5 << 1,
"shr": 5 >> 1,
}
# Unsigned u8: x=0b1010 (10), y=0b1100 (12)
x, y = 0b1010, 0b1100
u8_bin = {
"and": format(x & y, "b"),
"or": format(x | y, "b"),
"xor": format(x ^ y, "b"),
"not_u8": format((~x) & 0xFF, "b"),
"shl_1": format((x << 1) & 0xFF, "b"),
"shr_1": format(x >> 1, "b"),
}
expected = {
"signed_i32": {"and": 1, "or": 7, "xor": 6, "not_i32": -6, "shl": 10, "shr": 2},
"u8_binary": {"and": "1000", "or": "1110", "xor": "110", "not_u8": "11110101", "shl_1": "10100", "shr_1": "101"},
}
actual = {"signed_i32": signed_ops, "u8_binary": u8_bin}
return {
"name": "bitwise_twos_complement_ops",
"summary": "验证有符号 i32 按位取反 !5 == -6 与无符号 u8 按位运算二进制输出",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def case_compound_assignment_ops():
n = 5
trace = []
n += 3
trace.append(n)
n *= 2
trace.append(n)
n >>= 1
trace.append(n)
x = 5
x -= 2 # 3
x = rust_trunc_div(x * 4, 2) # 6
x = rust_trunc_rem(x, 4) # 2
x &= 3 # 2
x |= 1 # 3
x ^= 2 # 1
x <<= 2 # 4
expected = {"demo_trace": [8, 16, 8], "full_chain_final": 4}
actual = {"demo_trace": trace, "full_chain_final": x}
return {
"name": "compound_assignment_ops",
"summary": "验证基本赋值与算术/位运算复合赋值(+=、*=、>>=、&=、|=、^=、<<=)状态轨迹",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def case_range_cast_try_ref_deref():
half_open = list(range(1, 4)) # 1..4
inclusive = list(range(1, 4)) # 1..=3
r_0_5 = list(range(0, 5)) # 0..5
r_0_eq_5 = list(range(0, 6)) # 0..=5
cast_f64 = float(5)
# Simulate ? operator propagation on Result
def try_double(res: tuple[str, object]):
tag, val = res
if tag == "Err":
return res
return ("Ok", val * 2)
# Simulate &x / *b / ref y
a_cell = [10]
deref_b = a_cell[0]
ref_y = a_cell[0]
expected = {
"range_1_to_4": [1, 2, 3],
"range_1_eq_3": [1, 2, 3],
"range_0_to_5": [0, 1, 2, 3, 4],
"range_0_eq_5": [0, 1, 2, 3, 4, 5],
"cast_5_as_f64": 5.0,
"try_ok": ["Ok", 14],
"try_err": ["Err", "io_error"],
"deref_and_ref": [10, 10],
}
actual = {
"range_1_to_4": half_open,
"range_1_eq_3": inclusive,
"range_0_to_5": r_0_5,
"range_0_eq_5": r_0_eq_5,
"cast_5_as_f64": cast_f64,
"try_ok": list(try_double(("Ok", 7))),
"try_err": list(try_double(("Err", "io_error"))),
"deref_and_ref": [deref_b, ref_y],
}
return {
"name": "range_cast_try_ref_deref",
"summary": "验证 .. / ..= 区间、as 显式转型、? 错误传播以及 &、* 与 ref 引用语义",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def main():
cases = [
case_arithmetic_and_pow_ops(),
case_relational_comparison_ops(),
case_logical_short_circuit_ops(),
case_bitwise_twos_complement_ops(),
case_compound_assignment_ops(),
case_range_cast_try_ref_deref(),
]
print(json.dumps({"version": VERSION, "cases": cases}, ensure_ascii=False, indent=2))
if __name__ == "__main__":
main()
查看独立实例 ↗ 在独立页面查看源码、运行环境与工程包
本地运行
解压后按 README 说明在对应本地环境运行脚本。
本章附件与实例包
常见错误与边界检查
- 实际端口、文档资源与应用配置都应和测试条件一致。
技术规范与官方资料
练习与参考解答
查看参考解答
因为 `^` 在 Rust 中是按位异或(`0b10 ^ 0b11 = 0b01 = 1`),求乘方必须写 `2_i32.pow(3)`;同时 `!` 对布尔值是逻辑非,对整数类型则执行按位取反,8 位无符号整数 `00001010` 逐位翻转即得 `11110101`(十进制 245)。