收据状态回顾
Coddy 面向 C# 开发者的 Rust 课程的第 35 课,共 48 课。
挑战
简单实现 line::Line,包含公开字段 label: String、unit: i32 和 count: i32。实现 receipt::Receipt::new() -> Receipt、add(&mut self, line: Line) -> bool、total(&self) -> i32 和 labels(self) -> Vec<String>。只有两个数值字段都非负时才接受该条目;拒绝时,已有状态保持不变。已接受的条目会计入 unit * count,标签按插入顺序保留,包括重复项。labels 会消耗收据。solve 读取完整的、以空白分隔的 label unit count 三元组,整数范围为 -100 到 100,最多读取 100 个三元组。返回已接受条目的数量和总计,格式为 accepted:n total:n,然后换行并输出以逗号分隔的已接受标签;如果没有标签,则输出 empty。
实现所需的导出 API,并从 exercise::solve(input: &str) -> String 返回结果,末尾不要添加换行符。不要在可编辑代码中打印内容。锁定的驱动程序会独立检查所需的 API,读取所有标准输入,并在返回的文本末尾添加一个换行符后打印。
你的代码分别写在 exercise.rs、line.rs 和 receipt.rs 中。main.rs 包含提供的输入输出代码,不能编辑。
亲手试试
#![allow(dead_code, unused_imports, unused_variables, unused_mut)]
mod exercise;
mod line;
mod receipt;
use std::io::{self, Read};
fn main() {
let mut input=String::new();
io::stdin().read_to_string(&mut input).unwrap();
// 开始公开 API 探测
let mut r = receipt::Receipt::new(); assert_eq!(r.total(), 0);
assert!(r.add(line::Line { label: "ink".to_string(), unit: 13, count: 7 }));
assert!(!r.add(line::Line { label: "bad".to_string(), unit: -1, count: 3 }));
assert!(!r.add(line::Line { label: "bad2".to_string(), unit: 2, count: -3 }));
assert_eq!(r.total(), 91);
assert!(r.add(line::Line { label: "ink".to_string(), unit: 0, count: 5 }));
assert_eq!(r.total(), 91); assert_eq!(r.labels(), vec!["ink".to_string(), "ink".to_string()]);
assert!(receipt::Receipt::new().labels().is_empty());
// 结束公开 API 探测
println!("{}", exercise::solve(&input));
}
面向 C# 开发者的 Rust中的所有课
自己练习: Rust 在线编译器