impl 块与构造函数
Coddy 面向 Python 开发者的 Rust 课程的第 31 课,共 48 课。
Python 的 __init__ 会在实例分配后对其进行初始化,类方法也可以作为替代构造函数。Rust 没有保留的构造方法:new 是一种惯例上的关联函数,会返回 Self 或其他已声明类型。它没有 self 接收者,因为不需要已有实例。impl 块会为某个类型归集函数和方法,但不会改变该类型已声明的字段。构造函数可以集中设置默认值或验证输入,并返回 Option 或 Result。这个示例选择一个固定的初始模式。随后通过一个共享引用方法检查结果值;它并不是经过验证的数值区间。
Python:完整程序
class Mode:
def __init__(self, automatic):
self.automatic = automatic
@classmethod
def manual(cls):
return cls(False)
mode = Mode.manual()
print(mode.automatic)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。隐私控制可以限制调用者能够使用哪些构造方式。
挑战
简单实现具有私有端点的 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));
}
这节课包含一个小测验。开始学习即可作答,并记录你的进度。
面向 Python 开发者的 Rust中的所有课
自己练习: Rust 在线编译器