一、基本語法對比
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 運行時評估