派生值语义
Coddy 面向 C++ 开发者的 Rust 课程的第 40 课,共 48 课。
C++ 值类型通常依赖生成的逐成员复制操作,但 C++17 不会自动为每个聚合类型生成结构化相等比较。Rust 会显式派生选定的 trait 实现。Clone 提供请求的复制操作;Copy 允许隐式复制,并要求每个组成部分都支持它。包含 String 的结构体无法实现 Copy,但克隆它可以复制其中的文本。派生相等比较会对相关字段进行结构化比较。派生 Debug 会提供诊断格式,而不是稳定的交换格式。在需要相等比较与哈希对哪些字段用于标识值达成一致时,同时派生哈希和相等比较会很有用。这个示例会克隆一个自有字符串,然后修改克隆得到的字符串;它没有使用练习要求的坐标键表示法和唯一性算法。
完整的独立 C++17 程序:
#include <iostream>
#include <string>
struct Note {
std::string text;
bool operator==(const Note& other) const { return text == other.text; }
};
int main() {
Note a{"red"}; Note b = a; b.text = "gold";
std::cout << a.text << ' ' << b.text << ' ' << std::boolalpha << (a == b) << '\n';
}完整的独立 Rust 程序:
#[derive(Clone, PartialEq, Eq)]
struct Note { text: String }
fn main() {
let a = Note { text: "red".to_string() };
let mut b = a.clone();
b.text = "blue".to_string();
println!("{} {} {}", a.text, b.text, a == b);
}挑战
简单在 key.rs 中,定义 Key,包含公开的 row: i32 和 column: i32 字段,并派生 Copy、Clone、Debug、PartialEq、Eq 和 Hash。相等性比较和哈希必须使用这两个字段。派生的调试表示形式为 Key { row: n, column: n }。实现 unique::count(keys: &[Key]) -> usize,返回不同坐标对的数量,且不修改输入。solve 会读取以空白字符分隔的完整整数对,每个整数都在 -1000 到 1000 之间。返回不同坐标对的数量;输入为空时返回 0。
实现所需的导出 API,并从 exercise::solve(input: &str) -> String 返回结果,末尾不要添加换行符。不要在可编辑代码中打印内容。锁定的驱动程序会独立检查所需的 API,读取全部标准输入,并在返回的文本末尾添加一个换行符后打印。
你的代码应放在 exercise.rs、key.rs 和 unique.rs 中。main.rs 包含提供的输入/输出代码,不能编辑。
亲手试试
#![allow(dead_code, unused_imports, unused_variables, unused_mut)]
mod exercise;
mod key;
mod unique;
use std::io::{self, Read};
fn main() {
let mut input=String::new();
io::stdin().read_to_string(&mut input).unwrap();
// 开始公开 API 检查
use std::collections::HashSet;
let a = key::Key { row: 13, column: -6 }; let mut b = a; b.column = 7;
assert_eq!(a.column, -6); assert_ne!(a, b); assert_eq!(a, a.clone());
assert_eq!(format!("{:?}", a), "Key { row: 13, column: -6 }");
let c = key::Key { row: 14, column: -6 };
let mut set = HashSet::new(); set.insert(a); set.insert(a.clone()); set.insert(b); set.insert(c);
assert_eq!(set.len(), 3);
assert_eq!(unique::count(&[a, b, c, a, b]), 3);
assert_eq!(unique::count(&[]), 0); assert_eq!(unique::count(&[a, a]), 1);
assert_eq!(unique::count(&[c, a]), 2);
// 结束公开 API 检查
println!("{}", exercise::solve(&input));
}
这节课包含一个小测验。开始学习即可作答,并记录你的进度。
面向 C++ 开发者的 Rust中的所有课
自己练习: Rust 在线编译器