布尔条件
Coddy 面向 C 开发者的 Rust 课程的第 7 课,共 48 课。
C 条件可以接受标量值:零为假,非零为真。Rust 要求条件为 bool,整数不会隐式转换为布尔值。请写出明确的比较,例如 count != 0。在这两种语言中,运算符 &&、|| 和 ! 分别表示逻辑与、或和非。只有左侧为真时,&& 才会计算右侧;只有左侧为假时,|| 才会计算右侧。可以利用这种短路规则来保护整数除法等操作。在 Rust 中,比较结果为 bool。范围检查需要用 && 连接两个比较;low <= value <= high 不是 Rust 语法。Rust 会将布尔值格式化为 true 和 false,而 C 中的 %d 会将提升后的布尔值打印为 1 或 0。
C
#include <stdio.h>
#include <stdbool.h>
int main(void) {
int divisor = 0;
bool usable = divisor != 0 && 12 / divisor > 2;
printf("%d %d\n", usable, !usable);
return 0;
}Rust
fn main() {
let divisor: i32 = 0;
let usable = divisor != 0 && 12 / divisor > 2;
println!("{} {}", usable, !usable);
}在 Rust 中,将 C 的整数条件替换为 if count 无法通过编译。请明确说明你的意思是非零、正数,还是特定的位测试。
挑战
简单判断机器是否可以运行。输入格式为 temperature door emergency,其中温度范围为 -100 到 200,两个标志的值都只能是 0 或 1。门关着时,door=1;发生紧急情况时,emergency=1。必需的 API:pub fn temperature_ok(value: i32) -> bool 接受包含边界的 10 到 80 区间;pub fn may_run(temperature: i32, door_closed: bool, emergency: bool) -> bool 要求温度符合要求、门关着且没有紧急情况。将两个结果输出为小写 Rust 布尔值,中间用一个空格分隔。在 safety.rs 中实现公共 API。提供的 exercise.rs 会解析有效输入并调用该 API。按要求返回文本,末尾不要添加换行符;锁定的驱动程序会添加一个换行符。不要从 API 打印内容。所有输入值都符合给定范围。
实现所需的导出 API,并从 exercise::solve(input: &str) -> String 返回结果,末尾不要添加换行符。不要在可编辑代码中打印内容。锁定的驱动程序会独立检查所需的 API,读取全部标准输入,并在返回的文本末尾添加一个换行符后打印。
你的代码应写在 exercise.rs 和 safety.rs 中。main.rs 包含提供的输入/输出代码,不能编辑。
亲手试试
#![allow(dead_code, unused_imports, unused_variables, unused_mut)]
mod exercise;
mod safety;
use std::io::{self, Read};
fn main() {
let mut input=String::new();
io::stdin().read_to_string(&mut input).unwrap();
// 开始公开 API 探测
assert!(safety::temperature_ok(10));
assert!(safety::temperature_ok(80));
assert!(!safety::temperature_ok(9));
assert!(!safety::temperature_ok(81));
assert!(safety::may_run(47, true, false));
assert!(!safety::may_run(47, false, false));
assert!(!safety::may_run(47, true, true));
assert!(!safety::may_run(-1, true, false));
assert!(safety::may_run(47, true, false));
// 结束公开 API 探测
println!("{}", exercise::solve(&input));
}
这节课包含一个小测验。开始学习即可作答,并记录你的进度。
面向 C 开发者的 Rust中的所有课
自己练习: Rust 在线编译器