Menu
CoddyTech

派生值语义

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

派生属性会根据结构体的字段生成标准 trait 实现。PartialEq 和 Eq 根据字段判断相等性;Hash 提供匹配的哈希功能,供 HashSet 等集合使用。相等的值必须具有相同的哈希值。Clone 允许显式复制。Copy 还允许隐式复制,但只有所有字段都支持时才可以:整数坐标符合条件,而拥有所有权的 String 不符合。此示例会复制拥有所有权的文本,然后只修改副本。C 中的结构体赋值会复制内嵌的字符数组,而指针字段只会复制地址。

C

#include <stdio.h>
#include <string.h>
struct Note { char text[8]; };
int main(void) {
    struct Note a = {"red"};
    struct Note b = a;
    strcpy(b.text, "blue");
    printf("%s %s %d\n", a.text, b.text, strcmp(a.text, b.text) == 0);
    return 0;
}

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);
}

不要认为每个结构体都采用指针身份判断相等,或都能自动复制。请根据字段和预期的值语义选择派生属性。

challenge icon

挑战

简单

在 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));
}
quiz icon自我测试

这节课包含一个小测验。开始学习即可作答,并记录你的进度。

面向 C 开发者的 Rust中的所有课

自己练习: Rust 在线编译器