组合与所有权
Coddy 面向 PHP 开发者的 Rust 课程的第 34 课,共 48 课。
PHP 对象赋值和属性存储会保留对同一实例的引用,这与普通 PHP 数组的值语义不同。因此,摄像机可以通过原始镜头变量观察到之后的更改。Rust 可以直接将 Lens 作为字段来拥有,把其中的 String 移入 Camera,使旧绑定无法再使用。目标保留其原始的绿色值。移动外层 Rust 值会转移其拥有字段的所有权,而正常情况下,丢弃该值也会丢弃这些字段。PHP 析构函数和垃圾回收遵循不同的可达性规则,也不会强制执行这种访问约束。如果应由另一个所有者保留存储空间,请使用借用字段,并明确生命周期义务。
PHP:完整程序
<?php
declare(strict_types=1);
final class Lens {
public function __construct(public string $color) {}
}
final class Camera {
public function __construct(public Lens $lens) {}
}
$lens = new Lens("green");
$camera = new Camera($lens);
$lens->color = "blue";
echo $camera->lens->color, "\n";
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);
}拥有式组合与 PHP 中共享对象属性的存储关系并不相同。
挑战
简单实现 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));
}
这节课包含一个小测验。开始学习即可作答,并记录你的进度。
面向 PHP 开发者的 Rust中的所有课
自己练习: Rust 在线编译器