Menu
CoddyTech

If 表达式

Coddy 面向 Go 开发者的 Rust 课程的第 8 课,共 48 课。

Go 中的 if 用于选择语句。Rust 的 if 也可以产生值,因此可以在绑定语句的右侧使用分支选择。要让 if 产生值,必须包含 else 分支,并且各分支的结果类型必须兼容。

Rust 中每个分支的最终表达式会提供其值,且末尾不加分号。添加分号会让该分支的结果变成单元值 ()。Rust 没有三元条件运算符,直接使用 if 表达式即可。

完整的 Go 对比程序:

package main
import "fmt"
func main() {
    rainy := true
    footwear := "sandals"
    if rainy { footwear = "boots" }
    fmt.Println(footwear)
}

Go 的输出:

boots

完整的 Rust 教学程序:

fn main() {
    let rainy = true;
    let footwear = if rainy { "boots" } else { "sandals" };
    println!("{}", footwear);
}

Rust 的输出:

boots
challenge icon

挑战

简单

计算配送费用。输入是一个从 0 到 1000 千米的距离。需要实现的 API:pub fn charge(distance: u32) -> u32,距离为零时返回 0,距离为 1 到 3 时返回 5,距离更远时返回 5 + 2 * (distance - 3)。pub fn band(distance: u32) -> &'static str 在上述三种情况下分别返回 none、local 或 extended。输出格式为 band:charge。返回的标签是字符串字面量,因此起始代码中已提供 &'static str。请在 delivery.rs 中实现公开 API。提供的 exercise.rs 会解析有效输入并调用该 API。返回指定文本,末尾不要添加换行符;锁定的驱动程序会添加一个换行符。不要在 API 中打印内容。所有输入值都符合规定的范围。

实现所需的导出 API,并从 exercise::solve(input: &str) -> String 返回结果,末尾不要添加换行符。不要在可编辑代码中打印内容。锁定的驱动程序会独立检查所需的 API,读取全部标准输入,并在打印返回文本时添加一个换行符。

请将代码写在 exercise.rs、delivery.rs 中。main.rs 存放提供的输入/输出代码,不能编辑。

亲手试试

#![allow(dead_code, unused_imports, unused_variables, unused_mut)]
mod exercise;
mod delivery;
use std::io::{self, Read};
fn main() {
    let mut input=String::new();
    io::stdin().read_to_string(&mut input).unwrap();
    // 公开 API 检查开始
assert_eq!(delivery::charge(2), 5);
assert_eq!(delivery::band(2), "local");
assert_eq!(delivery::charge(0), 0);
assert_eq!(delivery::band(0), "none");
assert_eq!(delivery::charge(3), 5);
assert_eq!(delivery::band(3), "local");
assert_eq!(delivery::charge(17), 33);
assert_eq!(delivery::band(17), "extended");
assert_eq!(delivery::charge(2), 5);
    // 公开 API 检查结束
    println!("{}", exercise::solve(&input));
}
quiz icon自我测试

这节课包含一个小测验。开始学习即可作答,并记录你的进度。

面向 Go 开发者的 Rust中的所有课

自己练习: Rust 在线编译器