【Python基础】 19 Rust 与 Python if 语句对比笔记
一、基本语法对比
Rust if 语句
// 基本形式
let number = 7;if number < 5 {println!("condition was true");
} else {println!("condition was false");
}// 多条件 else if
if number % 4 == 0 {println!("number is divisible by 4");
} else if number % 3 == 0 {println!("number is divisible by 3");
} else if number % 2 == 0 {println!("number is divisible by 2");
} else {println!("number is not divisible by 4, 3, or 2");
}
Python if 语句
# 基本形式
number = 7if number < 5:print("condition was true")
else:print("condition was false")# 多条件 elif
if number % 4 == 0:print("number is divisible by 4")
elif number % 3 == 0:print("number is divisible by 3")
elif number % 2 == 0:print("number is divisible by 2")
else:print("number is not divisible by 4, 3, or 2")
二、条件表达式差异
布尔值处理
// Rust - 必须显式布尔值
let x = 5;// 编译错误:if 条件必须是 bool 类型
// if x {
// println!("x is truthy");
// }if x != 0 {println!("x is not zero"); // 正确
}if true { // 必须使用布尔值println!("This will always execute");
}
# Python - 支持真值测试
x = 5# Python 会进行真值测试
if x: # x 非零,为真print("x is truthy") # 会执行# 各种真值情况
if 0: # Falsepass
if "": # Falsepass
if []: # Falsepass
if None: # Falsepass
if "hello": # Truepass
if [1, 2, 3]: # Truepass
比较运算符
// Rust 比较运算符
let a = 5;
let b = 10;if a == b { // 相等println!("equal");
}
if a != b { // 不等println!("not equal");
}
if a < b { // 小于println!("less");
}
if a > b { // 大于println!("greater");
}
if a <= b { // 小于等于println!("less or equal");
}
if a >= b { // 大于等于println!("greater or equal");
}
# Python 比较运算符
a = 5
b = 10if a == b: # 相等print("equal")
if a != b: # 不等print("not equal")
if a < b: # 小于print("less")
if a > b: # 大于print("greater")
if a <= b: # 小于等于print("less or equal")
if a >= b: # 大于等于print("greater or equal")# Python 还支持链式比较
if 1 <= a <= 10: # 1 ≤ a ≤ 10print("a is between 1 and 10")
三、逻辑运算符对比
Rust 逻辑运算符
let age = 25;
let has_license = true;// && - 逻辑与
if age >= 18 && has_license {println!("Can drive");
}// || - 逻辑或
if age < 18 || !has_license {println!("Cannot drive");
}// ! - 逻辑非
if !has_license {println!("No license");
}// 短路求值
let mut count = 0;
if false && { count += 1; true } {// 不会执行,因为短路
}
println!("Count: {}", count); // 0
Python 逻辑运算符
age = 25
has_license = True# and - 逻辑与
if age >= 18 and has_license:print("Can drive")# or - 逻辑或
if age < 18 or not has_license:print("Cannot drive")# not - 逻辑非
if not has_license:print("No license")# 短路求值
count = 0
if False and (count := count + 1): # 使用海象运算符pass
print(f"Count: {count}") # 0
四、模式匹配(Rust 特有)
match 表达式
let number = 13;match number {1 => println!("One"),2 | 3 | 5 | 7 | 11 => println!("Prime"),13..=19 => println!("Teen"),_ => println!("Other"),
}// 匹配并提取值
let some_value = Some(5);
match some_value {Some(x) if x > 0 => println!("Positive: {}", x),Some(0) => println!("Zero"),Some(_) => println!("Negative"),None => println!("No value"),
}
if let 语法
let some_number = Some(7);// 传统 match
match some_number {Some(i) => println!("Matched {}", i),_ => {}, // 必须处理所有情况
}// 使用 if let 简化
if let Some(i) = some_number {println!("Matched {}", i);
}// 带条件的 if let
if let Some(i) = some_number && i > 5 {println!("Number is greater than 5: {}", i);
}
五、条件赋值对比
Rust 条件表达式
// if 是表达式,可以返回值
let condition = true;
let number = if condition {5
} else {6
};println!("The value of number is: {}", number);// 必须返回相同类型
// let result = if condition {
// 5 // i32
// } else {
// "six" // &str - 编译错误!
// };// 复杂条件赋值
let x = 10;
let category = if x < 0 {"negative"
} else if x == 0 {"zero"
} else {"positive"
};println!("Category: {}", category);
Python 条件表达式
# 三元运算符
condition = True
number = 5 if condition else 6
print(f"The value of number is: {number}")# 可以返回不同类型
result = 5 if condition else "six"
print(f"Result: {result}")# 传统多行写法
x = 10
if x < 0:category = "negative"
elif x == 0:category = "zero"
else:category = "positive"print(f"Category: {category}")
六、作用域和变量遮蔽
Rust 作用域
let number = 5;if number > 0 {let message = "Positive"; // 块内变量println!("{}", message);
} // message 离开作用域// println!("{}", message); // 错误:message 未定义// 变量遮蔽
let x = 5;
if x > 0 {let x = x * 2; // 遮蔽外部 xprintln!("Inside: {}", x); // 10
}
println!("Outside: {}", x); // 5
Python 作用域
number = 5if number > 0:message = "Positive" # 在 if 块内定义print(message)print(message) # 仍然可以访问!Python 没有块级作用域# 避免意外修改
x = 5
if x > 0:x = x * 2 # 修改外部变量print(f"Inside: {x}") # 10print(f"Outside: {x}") # 10 - 已被修改
七、高级模式匹配
Rust 复杂模式匹配
// 匹配元组
let pair = (0, -2);
match pair {(0, y) => println!("First is 0, y = {}", y),(x, 0) => println!("x = {}, second is 0", x),_ => println!("No zeros"),
}// 匹配枚举
enum Message {Quit,Move { x: i32, y: i32 },Write(String),ChangeColor(i32, i32, i32),
}let msg = Message::ChangeColor(0, 160, 255);
match msg {Message::Quit => println!("Quit"),Message::Move { x, y } => println!("Move to ({}, {})", x, y),Message::Write(text) => println!("Text message: {}", text),Message::ChangeColor(r, g, b) => {println!("Change color to RGB({}, {}, {})", r, g, b)},
}// @ 绑定
let value = Some(10);
match value {Some(x @ 1..=5) => println!("Small number: {}", x),Some(x @ 6..=10) => println!("Medium number: {}", x),Some(x) => println!("Large number: {}", x),None => println!("No number"),
}
八、错误处理模式
Rust 错误处理
// 使用 Result 和 match
let result: Result<i32, &str> = Ok(42);match result {Ok(value) => println!("Success: {}", value),Err(error) => println!("Error: {}", error),
}// 使用 if let 处理 Option
let optional_value: Option<i32> = Some(5);if let Some(value) = optional_value {println!("Got value: {}", value);
} else {println!("No value");
}
Python 错误处理
# 使用 try-except
try:result = 10 / 0print(f"Success: {result}")
except ZeroDivisionError as e:print(f"Error: {e}")# 使用 if 检查 None
optional_value = 5 # 或者 Noneif optional_value is not None:print(f"Got value: {optional_value}")
else:print("No value")
九、性能考虑
Rust 性能特性
// 编译时优化 - match 会被优化为跳转表
let x = 3;
match x {1 => println!("One"),2 => println!("Two"), 3 => println!("Three"),_ => println!("Other"),
}// 无运行时开销的模式匹配
let opt: Option<i32> = Some(42);
if let Some(x) = opt { // 编译时检查println!("{}", x);
}
Python 性能考虑
# 避免深层嵌套的 if-elif
value = 42# 不好:深层嵌套
if value == 1:pass
elif value == 2:pass
elif value == 3:pass
# ... 很多个 elif# 更好:使用字典分发
def handle_1():passdef handle_2():passhandlers = {1: handle_1,2: handle_2,# ...
}if value in handlers:handlers[value]()
十、总结对比
特性 | Rust 🦀 | Python 🐍 |
---|---|---|
语法 | if condition { } | if condition: |
布尔要求 | 必须显式 bool | 支持真值测试 |
作用域 | 块级作用域 | 函数级作用域 |
返回值 | 表达式,可返回值 | 语句,无返回值 |
模式匹配 | 强大的 match | 无内置模式匹配 |
类型安全 | 编译时检查 | 运行时检查 |
性能 | 零成本抽象 | 有运行时开销 |
灵活性 | 相对严格 | 非常灵活 |
选择建议:
- 选择 Rust:需要类型安全、高性能、模式匹配
- 选择 Python:需要快速开发、灵活的条件判断
关键记忆点:
- Rust 的
if
是表达式,Python 的if
是语句 - Rust 需要显式布尔值,Python 支持真值测试
- Rust 有强大的模式匹配,Python 依赖 if-elif 链
- Rust 有块级作用域,Python 是函数级作用域
- Rust 的 match 编译时优化,Python 的 if 运行时评估