映射与集合
Coddy 面向 Lua 开发者的 Rust 课程的第 23 课,共 48 课。
对于普通表,Lua 的 pairs 不保证按排序顺序或插入顺序遍历。示例代码会先将键收集到一个连续序列中,再显式排序,然后输出。Rust 的 BTreeMap 会直接按排序顺序遍历键,而 HashMap 不保证这种顺序。因此,这两个示例通过不同的机制生成确定性的名称列表。在 Lua 中,赋值 nil 会移除键,而不是存储一个存在但值为 nil 的条目,因此需要用单独的表示方式来处理可空载荷。Rust 映射的 get 方法会返回一个可选的借用值,使键不存在这一情况不受存储类型的影响。应根据所需的约定来选择查找、排序和所有权行为,而不是依赖偶然的输出顺序。
Lua:完整程序
local colors = {zinc = "gray", amber = "gold"}
local names = {}
for name in pairs(colors) do names[#names + 1] = name end
table.sort(names)
print(table.concat(names, ","))
print(colors.amber ~= nil)
Rust:完整程序
use std::collections::BTreeMap;
fn main() {
let mut colors = BTreeMap::new();
colors.insert("zinc", "gray");
colors.insert("amber", "gold");
println!("{}", colors.keys().cloned().collect::<Vec<_>>().join(","));
println!("{}", colors.contains_key("amber"));
}为了保证顺序确定,Lua 中必须显式排序;单独使用 pairs 并不能保证遍历顺序与 BTreeMap 相同。
挑战
简单在 vocabulary.rs 中实现 pub fn frequencies(text: &str) -> BTreeMap<String, usize> 和 pub fn repeated(text: &str) -> BTreeSet<String>,并从 std::collections 导入这两种类型。按空白字符拆分文本,区分大小写比较单词,并保留标点符号。frequencies 统计每个单词出现的次数;repeated 只包含出现次数至少为两次的单词。solve 按排序后的顺序返回重复单词,格式为 word=count,单词之间用逗号分隔;如果集合为空,则返回 none。两个 API 都必须能处理空输入和相互独立的调用,且不保留全局状态。
实现所需的导出 API,并从 exercise::solve(input: &str) -> String 返回结果,末尾不要加换行符。不要在可编辑代码中打印内容。锁定的驱动程序会独立检查所需的 API,读取全部标准输入,并在返回的文本末尾添加一个换行符后打印。
你的代码应写在 exercise.rs 和 vocabulary.rs 中。main.rs 包含提供的输入和输出代码,不能编辑。
亲手试试
#![allow(dead_code, unused_imports, unused_variables, unused_mut)]
mod exercise;
mod vocabulary;
use std::io::{self, Read};
fn main() {
let mut input=String::new();
io::stdin().read_to_string(&mut input).unwrap();
// 公开 API 探测开始
let counts = vocabulary::frequencies("fern oak fern elm oak fern");
assert_eq!(counts.len(), 3);
assert_eq!(counts.get("fern"), Some(&3));
assert_eq!(counts.get("elm"), Some(&1));
assert_eq!(counts.get("missing"), None);
let repeated = vocabulary::repeated("fern oak fern elm oak fern");
assert_eq!(repeated.into_iter().collect::<Vec<_>>(), vec![String::from("fern"), String::from("oak")]);
assert!(vocabulary::frequencies("").is_empty());
assert!(vocabulary::repeated("single").is_empty());
assert_eq!(vocabulary::frequencies("A a").len(), 2);
// 公开 API 探测结束
println!("{}", exercise::solve(&input));
}
这节课包含一个小测验。开始学习即可作答,并记录你的进度。
面向 Lua 开发者的 Rust中的所有课
自己练习: Rust 在线编译器