Menu
CoddyTech

If 表达式

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

Kotlin 和 Rust 都允许使用 if 表达式来选择一个值,因此都不需要单独的三元运算符。这些示例在不改变温度的情况下选择冰。Kotlin 将条件放在括号中,Rust 则将分支主体括在花括号中。熟悉的值选择语法是一个很好的起点,但代码块结果规则仍然有所不同。

Rust 只有在代码块最后一个表达式后没有分号时,才会返回该表达式的值。添加分号会让该分支变成 unit,并可能导致它与另一个分支不兼容。Kotlin 的分号用于分隔语句,不适用 Rust 的同一套尾部表达式规则。产生值的 Rust 分支必须具有兼容的类型,并且要处理两条路径;仅用于产生副作用的 if 可以省略 else。调整分支顺序前,先确认所需的结果类型。

Kotlin:完整程序

fun main() {
    val temperature = -2
    val state = if (temperature < 0) "ice" else "water"
    println(state)
}

Rust:完整程序

fn main() {
    let temperature = -2;
    let state = if temperature < 0 { "ice" } else { "water" };
    println!("{}", state);
}

在 Rust 的 "ice" 表达式后添加分号会丢弃字符串结果。

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自我测试

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

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

自己练习: Rust 在线编译器