Menu
CoddyTech

组合与所有权

Coddy 面向 JavaScript 开发者的 Rust 课程的第 34 课,共 48 课。

JavaScript 对象不会包含另一个对象,而是保存对它的引用。在 const tile = {texture} 之后,texture 绑定和 tile.texture 指向同一个对象,因此通过任一方进行的更改都会反映在另一方上;只要还有任何引用,垃圾回收器就会让该对象保持存活。Rust 的组合可以将拥有所有权的值直接存储为字段,由外层值负责管理内层值。移动外层值时,其中非 Copy 内容的所有权也会随之移动。下面的示例将一个纹理放入图块中,然后读取它的标签。在 Rust 中插入纹理时,会将纹理移动到图块中;之后原来的 texture 绑定就不能再使用,因此不会留下别名。也可以使用借用字段,但此时它的生命周期必须与其他位置的某个所有者关联,因为引用不会让其数据保持存活。当组合对象应当是自包含的时,可以选择所有权,例如一个会接收并持有每个传入项目的集合。组合不需要 extends:一种类型包含另一种类型,并将选定的行为委托给它。

完整的独立 JavaScript 程序:

const texture = { label: "linen" };
const tile = { texture };
console.log(tile.texture.label);

JavaScript 输出:

linen

完整的独立 Rust 程序:

struct Texture { label: String }
struct Tile { texture: Texture }
fn main() {
    let texture = Texture { label: "linen".to_string() };
    let tile = Tile { texture: texture };
    println!("{}", tile.texture.label);
}

Rust 输出:

linen
challenge icon

挑战

简单

实现 stop::Stop,其中包含公开的 name: String 和 minutes: i32 字段。journey::Journey::new() -> Journey 会创建一个空的自有集合。add(&mut self, stop: Stop) 会获取所有权,并按到达顺序追加。total(&self) -> i32 会返回分钟数总和,但不会移除停靠点。finish(self) -> Vec<Stop> 会消耗行程,并按顺序返回所有自有停靠点。solve 会读取完整的 name minutes 对。名称中没有空白字符;分钟数介于 0 和 1000 之间;停靠点最多有 100 个。第一行返回 total:n,第二行返回以逗号分隔的停靠点名称;如果行程为空,则使用 empty。

实现所需的导出 API,并从 exercise::solve(input: &str) -> String 返回结果,末尾不要添加换行符。不要在可编辑代码中打印内容。锁定的驱动程序会独立检查所需的 API,读取全部 stdin,并在返回的文本末尾添加一个换行符后打印。

你的代码放在 exercise.rs、stop.rs 和 journey.rs 中。main.rs 包含提供的输入/输出代码,不能编辑。

亲手试试

#![allow(dead_code, unused_imports, unused_variables, unused_mut)]
mod exercise;
mod stop;
mod journey;
use std::io::{self, Read};
fn main() {
    let mut input=String::new();
    io::stdin().read_to_string(&mut input).unwrap();
    // 公开 API 检查开始
let mut j = journey::Journey::new(); assert_eq!(j.total(), 0);
j.add(stop::Stop { name: "ridge".to_string(), minutes: 23 });
j.add(stop::Stop { name: "ridge".to_string(), minutes: 0 });
j.add(stop::Stop { name: "lake".to_string(), minutes: 8 });
assert_eq!(j.total(), 31); assert_eq!(j.total(), 31);
let out = j.finish(); assert_eq!(out.len(), 3);
assert_eq!((&out[0].name, out[0].minutes), (&"ridge".to_string(), 23));
assert_eq!((&out[1].name, out[1].minutes), (&"ridge".to_string(), 0));
assert_eq!((&out[2].name, out[2].minutes), (&"lake".to_string(), 8));
assert!(journey::Journey::new().finish().is_empty());
    // 公开 API 检查结束
    println!("{}", exercise::solve(&input));
}
quiz icon自我测试

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

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

自己练习: Rust 在线编译器