if 表達式
你可以像在其他語言中使用 if 陳述式那樣地使用 if 表達式:
fn main() { let x = 10; if x == 0 { println!("zero!"); } else if x < 100 { println!("biggish"); } else { println!("huge"); } }
此外,你也可以將 if 當作表達式使用。每個區塊中的最後一行式子將成為 if 表達式的賦值:
fn main() { let x = 10; let size = if x < 20 { "small" } else { "large" }; println!("number size: {}", size); }
This slide should take about 4 minutes.
Because if is an expression and must have a particular type, both of its branch blocks must have the same type. Show what happens if you add ; after "small" in the second example.
在運算式中使用 if 時,運算式須有 ;,才能與下一個陳述式分隔。移除 println! 前的 ; 即可查看編譯器錯誤。