布尔条件
Coddy 面向 PHP 开发者的 Rust 课程的第 7 课,共 48 课。
PHP 的布尔转换会将空数组视为 false,因此简写三元运算符会选择备用值。在条件中,零、空字符串、字符串 "0"、null 和 false 也会转换为 false。Rust 要求使用 bool,不会隐式转换集合或数字。如果要表达的是空或存在这一事实,请使用显式的空值或存在性检查。PHP 的空合并运算符与简写三元运算符的行为约定不同,因为它检查的是缺失值或 null 值,而不是所有类似 false 的值。Rust 示例会在短路读取索引之前检查是否为空。将防护条件放在左侧,并保留缺失值与有效零值数据之间的区别。
PHP:完整程序
<?php
declare(strict_types=1);
$items = [];
$chosen = $items ?: "fallback";
echo $chosen, "\n";
echo ($items ? "true" : "false"), "\n";
Rust:完整程序
fn main() {
let items: Vec<i32> = Vec::new();
let present = !items.is_empty();
println!("{}", present);
println!("{}", present && items[0] == 9);
}在 PHP 中,检查容器是否为空与检查 null 是两种不同的行为约定,在 Rust 中,这两种情况都需要明确表示。
挑战
简单判断机器是否可以运行。输入格式为 temperature door emergency,其中 temperature 的范围是 -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));
}
这节课包含一个小测验。开始学习即可作答,并记录你的进度。
面向 PHP 开发者的 Rust中的所有课
自己练习: Rust 在线编译器