Menu
CoddyTech

组合与所有权

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

Luau 组合会存储对类型化表的引用,因此将 Lens 放入 Camera 后,仍可使用原来的 lens 别名。修改它的字段后,通过 camera.lens 也能看到变化。Rust 可以直接将 Lens 作为字段拥有,把非 Copy 的 String 移走,并使旧绑定无法再使用。因此,Rust 示例仍保留 green,而源示例输出 blue。移动 Rust 外层值会转移其所拥有内容的所有权;借用的字段则需要与其他位置的所有者建立关系。垃圾回收的 Luau 使用的是不同的生命周期模型。对于独立的组合结构,选择所有权;对于临时访问,选择借用,不要想当然地认为组合需要继承。

完整的独立 Luau 程序:

type Lens = {color: string}
type Camera = {lens: Lens}
local lens: Lens = {color = "green"}
local camera: Camera = {lens = lens}
lens.color = "blue"
print(camera.lens.color)

Luau 输出:

blue

完整的独立 Rust 程序:

struct Lens { color: String }
struct Camera { lens: Lens }
fn main() {
    let lens = Lens { color: String::from("green") };
    let camera = Camera { lens: lens };
    println!("{}", camera.lens.color);
}

Rust 输出:

green
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自我测试

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

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

自己练习: Rust 在线编译器