Menu
CoddyTech

组合与所有权

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

Dart 组合会存储对嵌套对象的引用,因此将 Texture 传入 Tile 后,原始引用仍然可用。Rust 可以将拥有所有权的 Texture 直接存储为字段,并将其不可 Copy 的内容转移到 Tile 中。这些示例读取的是同一个 linen 标签,但构造完成后,Rust 中原来的纹理绑定不再可用。移动外层 tile 时,其中内容的所有权也会随之移动。如果需要让另一个所有者保留数据,也可以使用借用字段,但这样生命周期关系就会成为类型的一部分。当组合对象应该独立完整时,选择拥有所有权的组合。通过包含的值进行委托,不需要类继承。

完整的独立 Dart 程序:

class Texture {
  final String label;
  Texture(this.label);
}
class Tile {
  final Texture texture;
  Tile(this.texture);
}
void main() {
  final texture = Texture('linen');
  final tile = Tile(texture);
  print(tile.texture.label);
}

Dart 输出:

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,读取全部标准输入,并在打印返回的文本时添加一个末尾换行符。

你的代码应写在 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自我测试

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

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

自己练习: Rust 在线编译器