13.条件判断
条件判断语句 |
说明 |
if 语句 |
if 语句用于模拟现实生活中的 如果…就… |
if...else 语句 |
if...else 语句用于模拟 如果…就…否则… |
else...if 和嵌套if 语句 |
嵌套if 语句用于模拟 如果…就…如果…就… |
match 语句 |
match 语句用于模拟现实生活中的 老师点名 或 银行叫 |
if 语句
1 2 3 4 5 6 7 8 9
| if 条件表达式 { // 条件表达式为true时要执行的逻辑 }
let total:f32=666.00; if total>500.00{ println!("打8折,{}",total*0.8) } //输出 打8折,532.8
|
if …else 语句
1 2 3 4 5 6 7 8 9 10 11 12 13
| if 条件表达式 { // 如果 条件表达式 为真则执行这里的代码 } else { // 如果 条件表达式 为假则执行这里的代码 }
let total:f32=166.00; if total>500.00{ println!("打8折,{}",total*0.8) }else{ println!("无折扣优惠,{}",total) } 输出 无折扣优惠,166
|
if…else if… else 语句
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
| if 条件表达式1 { // 当 条件表达式1 为 true 时要执行的语句 } else if 条件表达式2 { // 当 条件表达式2 为 true 时要执行的语句 } else { // 如果 条件表达式1 和 条件表达式2 都为 false 时要执行的语句 }
let total:f32=366.00; if total>200.00 && total<500.00{ println!("打9折,{}",total*0.9) }else if total>500.00{ println!("打8折,{}",total*0.9) } else{ println!("无折扣优惠,{}",total) } //输出 打9折,329.4
|
match 语句
Rust 中的 match
语句有返回值,它把 匹配值 后执行的最后一条语句的结果当作返回值。
语法
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
| match variable_expression { constant_expr1 => { // 语句; }, constant_expr2 => { // 语句; }, _ => { // 默认 // 其它语句 } };
let code = "10010"; let choose = match code { "10010" => "联通", "10086" => "移动", _ => "Unknown" }; println!("选择 {}", choose); //输出 选择 联通
let code = "80010"; let choose = match code { "10010" => "联通", "10086" => "移动", _ => "Unknown" }; println!("选择 {}", choose); //输出 选择 Unknown
|
添加微信 |
公众号更多内容 |
 |
 |