Menu
CoddyTech

收据状态回顾

Coddy 面向 C 开发者的 Rust 课程的第 35 课,共 48 课。

challenge icon

挑战

简单

实现 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 在线编译器