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); }
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.
An if
expression should be used in the same way as the other expressions. For example, when it is used in a let
statement, the statement must be terminated with a ;
as well. Remove the ;
before println!
to see the compiler error.