impl 与构造函数
Coddy 面向 Ruby 开发者的 Rust 课程的第 31 课,共 48 课。
Ruby 的 Class#new 会分配一个实例并调用 initialize,而类方法可以提供带名称的构造方式,例如 Switch.off。Rust 结构体没有一种通用构造函数,可以在结构体字面量创建时自动运行。impl 块提供关联函数和方法,而 new 只是一个常见的函数名。引用实现该方法的类型时,返回 Self。如果输入可能无效,工厂函数可以返回 Result,而不是创建部分初始化的对象。Rust 的方法定义与字段声明彼此分开。不要把 Ruby 的 initialize 翻译成每种目标语言构造过程中的隐式回调;应在构造位置显式调用预期的函数。
Ruby:完整程序
class Switch
attr_reader :active
def initialize(active)
@active = active
end
def self.off
new(false)
end
end
puts Switch.off.active
Rust:完整程序
struct Mode { automatic: bool }
impl Mode {
fn manual() -> Self { Mode { automatic: false } }
fn automatic(&self) -> bool { self.automatic }
}
fn main() { println!("{}", Mode::manual().automatic()); }在 Rust 中,new 是一种惯例;而 Ruby 的 new 和 initialize 会参与类的构造过程。
挑战
简单实现具有私有端点的 span::Span。Span::new(start: i32, end: i32) -> Option<Span> 在 end < start 时返回 None;否则保留两个端点。Span::width(&self) -> i32 返回 end - start,因此端点相同时宽度为零。Span::contains(&self, point: i32) -> bool 包含两个端点。solve 读取完整的三元组 start end point,每个整数都在 -1000 到 1000 之间。对每个有效跨度,返回 width:contains,其中布尔值使用小写的 true 或 false;对于端点顺序颠倒的跨度,返回 invalid。用换行符连接各行;没有三元组时返回 empty。
实现所需的导出 API,并从 exercise::solve(input: &str) -> String 返回结果,不要添加结尾换行符。不要在可编辑代码中打印内容。锁定的驱动程序会独立检查所需的 API,读取全部标准输入,并在打印返回文本时添加一个结尾换行符。
代码写在 exercise.rs、span.rs 中。main.rs 包含提供的输入输出代码,不能编辑。
亲手试试
#![allow(dead_code, unused_imports, unused_variables, unused_mut)]
mod exercise;
mod span;
use std::io::{self, Read};
fn main() {
let mut input=String::new();
io::stdin().read_to_string(&mut input).unwrap();
// 开始公开 API 检查
assert!(span::Span::new(18, 12).is_none());
let s = span::Span::new(-13, 24).unwrap();
assert_eq!(s.width(), 37);
assert!(s.contains(-13)); assert!(s.contains(24)); assert!(!s.contains(25));
assert_eq!(s.width(), 37);
let z = span::Span::new(-8, -8).unwrap();
assert_eq!(z.width(), 0); assert!(z.contains(-8)); assert!(!z.contains(-9));
// 结束公开 API 检查
println!("{}", exercise::solve(&input));
}
这节课包含一个小测验。开始学习即可作答,并记录你的进度。
面向 Ruby 开发者的 Rust中的所有课
自己练习: Rust 在线编译器