方法与 impl

上一章末尾留下两个口子。LogEntry 的字段全是公开的,别处写一行 status: 999 照样编译通过,parse_line 校验得再严也白搭;与记录有关的函数又散在各处。把它们摆出来是这样:

rust
struct LogEntry {
    pub user: String,
    pub path: String,
    pub status: u16,
    pub latency_ms: u32,
}
 
fn is_slow(entry: &LogEntry, slow_ms: u64) -> bool {
    u64::from(entry.latency_ms) >= slow_ms
}
 
fn archive(entry: LogEntry) -> String {
    format!("{} {} {}", entry.user, entry.path, entry.status)
}
 
fn main() {
    let entry = LogEntry {
        user: String::from("mallory"),
        path: String::from("/pay"),
        status: 999,
        latency_ms: 0,
    };
    println!("{}", is_slow(&entry, 80));
    println!("{}", archive(entry));
}
text
false
mallory /pay 999

这段程序没有一处编译错误,毛病全在设计上。is_slow 只看一眼,archive 把整条记录吃掉,两者的差别藏在参数类型里,要翻到定义才知道;谁都可以再写第三个函数,把 status 改成任意数;999 这种值,类型不会拦。

impl 解决的正是这几件事:把操作放到类型旁边,让接收者(receiver,方法的第一个参数 self)说明调用之后这个值归谁,把字段藏进模块边界,让构造只剩一个出口。这一章从结构体的写法讲起,依次是方法与关联函数、可见性、三种接收者、构造器与不变式、消费型方法与构建器、trait 的定义与实现、孤儿规则与 newtype、点号背后的方法查找,最后把 logbook 升到 v0.6:Status 守住 100 到 599,LogEntry 字段私有,ReportBuilder 产出报表设置。

结构体的写法

前几章已经反复用过结构体,现在补上完整的写法。带名字的字段是最常见的一种,#[derive(Debug, Clone)] 让编译器替你写出 {:?} 打印和克隆的实现(本章后半讲 trait 是什么)。变量名与字段同名时可以省掉冒号,已有实例可以用 .. 补齐剩下的字段:

rust
#[derive(Debug, Clone)]
struct LogEntry {
    user: String,
    path: String,
    status: u16,
    latency_ms: u32,
}
 
#[derive(Debug, Clone, Copy)]
struct Status(u16);
 
struct Quiet;
 
fn probe(user: String, path: String) -> LogEntry {
    LogEntry { user, path, status: 200, latency_ms: 0 }
}
 
fn main() {
    let base = probe(String::from("alice"), String::from("/home"));
    let slow = LogEntry { latency_ms: 120, ..base.clone() };
    println!("{slow:?}");
    let Status(code) = Status(404);
    println!("{code} {}", Status(500).0);
    let _q = Quiet;
}
text
LogEntry { user: "alice", path: "/home", status: 200, latency_ms: 120 }
404 500

probe 里的 LogEntry { user, path, .. } 是字段初始化简写。Status(u16) 是元组结构体:字段没有名字,用 .0 读,也可以在模式里拆开。只有一个字段的元组结构体常用来给已有类型换一个身份,这叫 newtype,第 3 章的 RetryCount 就是一个。Quiet 是单元结构体,没有字段,只用来占一个类型的位置,后面做类型状态时会用到。

..base.clone() 里的 clone 不是随手加的。去掉它,..base 会把 base 里没被点名的字段移走:

rust
let other = LogEntry { user: String::from("bob"), ..base };
println!("{:?} {:?}", other, base);
text
error[E0382]: borrow of partially moved value: `base`
  --> main.rs:17:34
   |
16 |     let other = LogEntry { user: String::from("bob"), ..base };
   |                 ---------------------------------------------- value partially moved here
17 |     println!("{:?} {:?}", other, base);
   |                                  ^^^^ value borrowed here after partial move
   |
   = note: partial move occurs because `base.path` has type `String`, which does not implement the `Copy` trait

value partially moved here 说的是:path 这个 String 被移进了 other,base 剩下的部分还在,整体却不能再借出去,这正是第 2 章的部分移动。只补 Copy 字段(比如这里的 status、latency_ms)不会触发它。

方法与关联函数

impl LogEntry { … } 里的函数都和 LogEntry 关联,所以统称关联函数(associated function)。其中第一个参数叫 self 的又叫方法(method),可以用点号调用;没有 self 的,比如 new,只能用 LogEntry::new(…) 的写法:

rust
struct LogEntry {
    user: String,
    latency_ms: u32,
}
 
impl LogEntry {
    fn new(user: &str, latency_ms: u32) -> Self {
        Self { user: user.to_string(), latency_ms }
    }
 
    fn is_slow(&self, slow_ms: u64) -> bool {
        u64::from(self.latency_ms) >= slow_ms
    }
}
 
fn main() {
    let entry = LogEntry::new("bob", 80);
    println!("{}", entry.is_slow(80));
    println!("{}", LogEntry::is_slow(&entry, 81));
    println!("{}", entry.user);
}
text
true
false
bob

entry.is_slow(80) 和 LogEntry::is_slow(&entry, 81) 是同一个函数的两种写法,点号只是替你把 entry 当作第一个参数传进去,必要时补上 &。Self 在 impl 里就是当前类型,写 Self 比写类型名耐改,类型重命名时不用到处替换。

什么该写成方法?问一句“这个操作的主语是不是这个类型”。entry.is_slow(80) 主语清楚;一个要同时协调文件、统计表和三个类型的流程,硬塞进某个小结构体的方法里,主语反而失真,留成普通函数更诚实。

new 只是约定俗成的名字,不是关键字,也不触发任何特殊流程。from_parts、with_capacity、parse 都可以是关联函数。名字应当告诉调用者得到的是哪一种值,不必为了模仿别的语言统一叫构造器。

方法也是模块边界

把函数搬进 impl 不会自动封装字段,决定外部能做什么的是可见性。Rust 默认一切私有,私有的边界是模块(module),不是类型:同一个模块里的代码能碰所有字段,换到别的模块就只能碰标了 pub 的。模块系统本身在第 9 章讲包和 crate 时再展开,这里只需要知道 mod 名字 { … } 围出一块有边界的区域:

rust
mod logbook {
    pub struct LogEntry {
        user: String,
        status: u16,
    }
 
    impl LogEntry {
        pub fn new(user: &str, status: u16) -> Option<LogEntry> {
            if (100..=599).contains(&status) {
                Some(LogEntry { user: user.to_string(), status })
            } else {
                None
            }
        }
    }
}

类型是 pub 的,字段不是。模块外面既不能直接写字面量,也不能读字段:

text
error[E0451]: field `user` of struct `LogEntry` is private
 --> main.rs:9:37
  |
9 |     let entry = logbook::LogEntry { user: String::from("mallory"), status: 999 };
  |                                     ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ private field
 
error[E0451]: field `status` of struct `LogEntry` is private
text
error[E0616]: field `status` of struct `LogEntry` is private
  --> main.rs:21:22
   |
21 |     println!("{}", b.status);
   |                      ^^^^^^ private field

想要一个 LogEntry,只剩 new 这一条路,而 new 在里面检查了范围。校验的位置变了:不再靠每个调用者自觉,而是写在唯一的入口里。需要让同一个 crate 里的管理代码能调用、crate 外看不到的,可以写 pub(crate),可见性不止“全公开”和“全私有”两档。

字段私有以后,外部读取靠方法。Rust 不会替你生成 getter,entry.user 是字段,entry.user() 是方法,括号区分得很清楚。getter 不必机械地一字段一个:该返回 &str 的返回借用,小而 Copy 的值直接返回值。我会避免提供返回 &mut 字段的方法,调用者拿着那份可变引用想怎么写就怎么写,方法退出后你再没有检查的机会,封装等于白做。同理,比起给每个字段配一个 set_xxx,更值得提供有业务含义的动作:withdraw 能说明失败原因,set_balance 只能赋值。

私有字段还给内部表示留出了调整空间。外部只依赖方法,以后 latency_ms 想改成带单位的类型,调用者不会跟着改。也不是所有字段都要私有:刚从输入读到的一包原始字段,像第 4 章里 LogEntry 的样子,公开字段更直接。判断标准是这个类型有没有在维护规则,声称“任何实例都是合法记录”,就得管住创建和修改的入口。

私有字段拦的是模块外面的代码,同一个模块里的每条路径仍要自己守规矩。从文件或网络恢复对象时尤其如此:“反序列化成功”不等于“业务上合法”。

先看调用之后还要不要这个值

选接收者最实用的起点不是“实现要改几个字段”,而是“调用者接下来还要怎么用这个值”。三种写法是 self: &Self、self: &mut Self 和 self: Self 的缩写:

三把钥匙对应三种接收者:只读和独占修改之后原值都仍可用,交出去之后原值退场

&self 借来看,&mut self 借来改,self 把整个值交给方法。

下面的实验给了五张工单,你为每个方法选接收者,页面会指出选错后调用方的哪一步出问题。先自己想一遍再点。

只读查询从 &self 开始

方法只需要观察对象时,&self 最宽松,调用者可以连续查询,也能同时保留多份共享引用。有一个细节容易被忽略:返回 &str 的 getter,那个引用借自 self,只要它还在用,整个对象就处于被共享借用的状态。

rust
struct Tally {
    last_user: String,
    count: u32,
}
 
impl Tally {
    fn last_user(&self) -> &str {
        &self.last_user
    }
 
    fn bump(&mut self) {
        self.count += 1;
    }
}
 
fn main() {
    let mut tally = Tally { last_user: String::from("alice"), count: 0 };
    let user = tally.last_user();
    tally.bump();
    println!("{user} {}", tally.count);
}
text
error[E0502]: cannot borrow `tally` as mutable because it is also borrowed as immutable
  --> main.rs:19:5
   |
18 |     let user = tally.last_user();
   |                ----- immutable borrow occurs here
19 |     tally.bump();
   |     ^^^^^^^^^^^^ mutable borrow occurs here
20 |     println!("{user} {}", tally.count);
   |                ---- immutable borrow later used here

bump 其实只改 count,与 last_user 无关,编译器照样拒绝。它看的是签名:&mut self 对调用者承诺了可以改整个 Tally,接口承诺的权限比实现碰了哪个字段更重要。修法有两条。让 user 在 bump 之前用完最后一次;或者 last_user().to_owned() 拿一份独立的字符串,多一次分配,换来能活过后续修改。短暂展示用前者,数据要跨越之后的修改或原对象的寿命,就用后者。别为了方便让每次读取都无条件克隆。

修改要 &mut self,小值可以 self

&mut self 表示调用期间独占接收者,调用点的绑定要写 mut。这个独占不只是“只有一个变量指向它”:在这次借用还会被使用的范围里,别的引用都不能再读写这份数据,所以方法执行到一半时,别处不会看见只更新了一半的状态。

&self 的“只读”也不是绝对的:Cell 这类类型可以在 &self 方法里改小数据,第 10 章讲内部可变性,这里只需知道 &self 的准确含义是“共享访问”,一个看起来只读的方法偷偷改了会影响结果的状态,读代码的人会很难受。

self 按值接收,是否真的“用掉”要看类型是不是 Copy。Status 只包一个 u16,实现了 Copy,fn code(self) -> u16 之后调用者手里的原值照样能用,对这类小值,直接按值接收最省事。持有 String、Vec 的类型就不同,按值调用会真移动,下一节细看。别为了让某个消费型方法“调用后还能用”就给类型实现 Copy:资源所有者和可增长容器不适合隐式复制。

接收者还有 self: Box<Self>、self: Rc<Self> 这类更具体的写法,用于“对象存放在哪里”本身属于协议的场合。日常业务代码几乎碰不到,用 &self 够了就不要写得复杂。

0:00/

构造器与不变式

不变式(invariant)是“这个类型的每个实例都成立的条件”,比如状态码在 100 到 599 之间。构造器的职责是让条件在对象诞生那一刻就成立,之后的方法就可以放心依赖它,不必每个都先猜一遍“这个对象是不是坏的”。

下面的工作台把输入走三条路:普通的 new、带校验的 try_with_step、直接写字面量。输入 3、0、−2,看非法值在哪一站被挡下,第三条路为什么根本拦不住。

回到 logbook。状态码的不变式有两层:字段私有,外部拼不出非法值;类型本身只能通过校验产生。后者用第 3 章 RetryCount 的形状,写成 Status newtype,再给它实现 TryFrom<u16>:

rust
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct Status(u16);
 
impl TryFrom<u16> for Status {
    type Error = ParseError;
 
    fn try_from(code: u16) -> Result<Self, Self::Error> {
        if (100..=599).contains(&code) {
            Ok(Status(code))
        } else {
            Err(ParseError::StatusOutOfRange(code))
        }
    }
}

(片段,在 mod logbook 里,完整程序在本章末。)Status 的字段私有,模块外甚至不能写 Status(999):

text
error[E0603]: tuple struct constructor `Status` is private
 --> main.rs:6:27
  |
2 |     pub struct Status(u16);
  |                       --- a constructor is private if any of the fields is private
...
6 |     let status = logbook::Status(999);
  |                           ^^^^^^ private tuple struct constructor

拿到 Status 的代码就可以相信范围检查过了。derive 里的 Hash、Ord 是为了让它能做 HashMap 的键和 BTreeMap 的键,报表要用到。LogEntry 也一样,它的构造只剩 LogEntry::parse(line) 一个出口:

rust
impl LogEntry {
    pub fn parse(line: &str) -> Result<LogEntry, ParseError> {
        let user = field(line, 0).ok_or(ParseError::MissingField("user"))?;
        let path = field(line, 1).ok_or(ParseError::MissingField("path"))?;
        let status = Status::try_from(number::<u16>(line, 2, "status")?)?;
        let latency_ms = number(line, 3, "latency_ms")?;
        Ok(LogEntry {
            user: user.to_string(),
            path: path.to_string(),
            status,
            latency_ms,
        })
    }
}

field 和 number 是第 5 章的老朋友,? 的规则也在那里。注意一个细节:所有检查都在局部变量里做完,最后一次性返回 Ok(LogEntry { … })。失败时被丢弃的只有临时值,不会有谁拿到半个对象;Result<Self, E> 把“成功得到完整对象,失败得到原因”两个出口都写进了签名。

关联函数叫什么,是在向调用者交代会发生什么:

名字通常意味着
new最主要、通常直接成功的创建入口
try_new创建时要检查,失败是正常分支
parse / FromStr输入是文本,格式错误很自然
from_parts用已经拆好的部件组装
default / Default有一个不会让人吃惊的默认值

语言不禁止 new 返回 Result,只是生态里读者更习惯把会失败的版本叫 try_new,一套 API 里命名可预测就行。From 留给不会失败的转换,会失败的用 TryFrom;不要为了少写一个 ? 在转换失败时偷偷挑个默认值。

构造器也不必接收所有字段。把字段分三类:缺了就形不成合法对象的必填信息;有稳定默认值的可选配置;应由对象自己推导或维护的状态。LogEntry::parse 只收一行文本,就是因为四个字段都该由解析得出,不由调用者挑着拼。

错误返回是方法协议的一部分

接收者说明值怎么流动,返回类型说明调用者要面对什么。失败只有一种含义、调用者只关心“有没有”,用 Option;要区分原因再决定动作,用 Result;panic 留给契约被程序员打破的情形(Option/Result/panic 的取舍在第 5 章讲透)。落到方法上还有一条:失败不该留下副作用。方法在所有检查通过之后才修改字段,返回 Err 时对象保持原样,这个“失败时没变过”应当算进契约。要是方法先清空再发现新值不合格,调用者拿到错误还得猜对象坏没坏。

一个判断可以帮你选 panic:如果触发它的输入来自用户,那是 Result 的事,不是程序缺陷。后面类型状态里有个 expect,它之所以可以接受,是因为私有字段和状态转换保证了那个 Option 一定有值;若用户传个 0 也走到同一个 expect,就是把输入错误伪装成程序 bug 了。

消费型方法会结束旧值

方法接收 self 时,调用者把所有权整个交了进去。常见的三类用途:转换成另一种表示、取出内部资源、结束只能发生一次的流程。看 LogEntry 的 into_user:

rust
impl LogEntry {
    fn user(&self) -> &str { &self.user }
    fn into_user(self) -> String { self.user }
}
 
fn main() {
    let entry = /* 构造一个 LogEntry */;
    let name = entry.into_user();
    println!("{name} {}", entry.user());
}
text
error[E0382]: borrow of moved value: `entry`
  --> main.rs:32:27
   |
28 |     let entry = LogEntry { user: String::from("alice"), status: Status(404) };
   |         ----- move occurs because `entry` has type `LogEntry`, which does not implement the `Copy` trait
...
31 |     let name = entry.into_user();
   |                      ----------- `entry` moved due to this method call
32 |     println!("{name} {}", entry.user());
   |                           ^^^^^ value borrowed here after move
   |
note: `LogEntry::into_user` takes ownership of the receiver `self`, which moves `entry`
  --> main.rs:22:18
   |
22 |     fn into_user(self) -> String {
   |                  ^^^^

注意末尾的 note:编译器直接指出是 into_user 拿走了接收者。into_user(self) 把内部的 String 原样交出,不用克隆,代价是 entry 从此退场;user(&self) 只是暂借。方法名里的前缀就是在预告这笔账,标准库和多数库都遵守:

  • as_… 通常是便宜的借用视图,如 as_str;
  • to_… 通常会新建一个值,可能分配,如 to_owned;
  • into_… 通常消费原值并尽量复用资源,如 into_bytes。

这些不是编译器强制的,但能省掉调用者很多次翻签名。archive(self) 那种名字,说明它是个“结束一件事”的动词,归档以后这条记录确实不该再用;只是换个形式取出内部资源,就叫 into_…。

带 Drop 的类型在消费方法里不能随便把字段移出去,编译器会拒绝,因为释放逻辑稍后还要拿到完整的 self。常见做法是把可取出的资源存成 Option<T> 再 take();Drop 本身在第 10 章讲。

构建器为什么消费自己

构建器的中间状态只为最终对象服务。build(self) 能把里面的字符串和容器直接搬出去,还能阻止同一个构建器被误用两次。logbook 的 ReportBuilder 负责收集报表设置:

rust
pub struct ReportBuilder {
    top: usize,
    slow_ms: u64,
}
 
impl ReportBuilder {
    pub fn new() -> Self {
        ReportBuilder { top: 5, slow_ms: 80 }
    }
 
    pub fn top(mut self, top: usize) -> Self {
        self.top = top;
        self
    }
 
    pub fn slow_ms(mut self, slow_ms: u64) -> Self {
        self.slow_ms = slow_ms;
        self
    }
 
    pub fn build(self) -> Result<Report, BuildError> {
        if self.top == 0 {
            return Err(BuildError::ZeroTop);
        }
        if !(1..=60_000).contains(&self.slow_ms) {
            return Err(BuildError::SlowMsOutOfRange(self.slow_ms));
        }
        Ok(Report { top: self.top, slow_ms: self.slow_ms })
    }
}

(片段,同样在 mod logbook 里。)top(mut self, …) 的 mut 只表示方法体里可以改这份已经移进来的 self;调用者的绑定不用 mut,因为每一步消费旧构建器、交回一个新的。这也不意味着每一步都深拷贝:资源沿着链被移动,String 之类的堆数据没有复制。

构建器接力:b0 移动到 b1,再到 b2,前面的名字被划掉,最后 build 得到 Server

每一步 self -> Self 都把前一个名字作废,只有最后的 build 通向成品。

方法链好用与否,取决于错误放在哪里

链式写法让代码按动作顺序读:创建、配置、构建。下面的演示按棒前进,看 b0、b1 何时失去使用资格,注意 build(self) 是终点,分行书写不改变任何移动。

如果有人把中间的绑定留下来再用,编译器就会指出:

rust
let b0 = ReportBuilder::new();
let b1 = b0.top(3);
let b2 = b0.slow_ms(50);
text
error[E0382]: use of moved value: `b0`
  --> main.rs:17:14
   |
15 |     let b0 = ReportBuilder::new();
   |         -- move occurs because `b0` has type `ReportBuilder`, which does not implement the `Copy` trait
16 |     let b1 = b0.top(3);
   |                 ------ `b0` moved due to this method call
17 |     let b2 = b0.slow_ms(50);
   |              ^^ value used here after move

想从同一个起点分叉出两套设置,就该先 clone 再配置,或者换成 &mut self -> &mut Self 的风格,它适合在循环和条件分支里反复调整同一个构建器。这种风格自己也有坑,临时值会在语句结束时被释放:

rust
let b = Builder::new().top(3);   // top(&mut self) -> &mut Self
println!("{}", b.build());
text
error[E0716]: temporary value dropped while borrowed
  --> main.rs:12:13
   |
12 |     let b = Builder::new().top(3);
   |             ^^^^^^^^^^^^^^       - temporary value is freed at the end of this statement
   |             |
   |             creates a temporary value which is freed while still in use
13 |     println!("{}", b.build());
   |                    - borrow later used here

Builder::new() 产生的值没有名字,语句一结束就释放,top 返回的引用却被存了下来。把它先绑定到局部变量就行。两种风格各有账:self -> Self 适合一条从头到尾的表达式,&mut self 适合要复用的场合,别因为链式看起来漂亮就硬让所有 API 消费自己。

链上出现 Result 的地方也要决定。ReportBuilder 的设置方法只存原始值,所有检查留到 build 里一并做:top 和 slow_ms 彼此独立,没有哪个值是后续设置能“救回来”的,放到最后检查,链干净,也便于一次发现多个问题。设置方法如果自己返回 Result<Self, E>,就能在无效值出现的位置立刻报错,代价是链上到处都是 ?。我的做法是:格式本身就不可能合法、后面的配置修不好的,尽早失败;字段之间的组合约束,等到 build。

方法链也最容易吞掉上下文。"abc".parse::<u64>().unwrap_or(3_000) 写起来顺,但用户配置里写错的 abc 会悄悄变成默认值,和第 5 章开头 read_slow_ms 的毛病是同一种。错误应该保留调用者能据此采取行动的信息,ZeroTop 和 SlowMsOutOfRange 是两种不同的修复方向。

类型状态:让错误的调用没有方法可选

普通构建器把必填字段存成 Option,最后由 build 检查,简单、错误集中,通常已经够好。更严的做法是把“某个设置有没有给”编码进类型,只有完整状态才有 build:

rust
use std::marker::PhantomData;
 
struct Unset;
struct Set;
 
struct Builder<S> {
    slow_ms: u64,
    state: PhantomData<S>,
}
 
impl Builder<Unset> {
    fn new() -> Self {
        Builder { slow_ms: 0, state: PhantomData }
    }
 
    fn slow_ms(self, slow_ms: u64) -> Builder<Set> {
        Builder { slow_ms, state: PhantomData }
    }
}
 
impl Builder<Set> {
    fn build(self) -> u64 {
        self.slow_ms
    }
}

Unset 和 Set 是两个单元结构体,只当标记用;PhantomData<S>(标准库提供的零大小占位类型)让结构体能“带着”类型参数 S 又不真的存数据。漏了 .slow_ms(…),编译器不会等到运行时才说“缺设置”,而是说类型根本没有这个方法:

text
error[E0599]: no method named `build` found for struct `Builder<Unset>` in the current scope
  --> main.rs:29:35
   |
29 |     println!("{}", Builder::new().build());
   |                                   ^^^^^ method not found in `Builder<Unset>`
   |
   = note: the method was found for
           - `Builder<Set>`

收益是把运行时的分支搬到了编译期。账单也同样清楚:类型、泛型参数和报错都会变多;字段来自循环、配置文件或条件分支时,不同分支得到不同的类型,反而要费劲重组。步骤少、顺序重要、写错代价高的流程,比如握手、事务提交,才值得;十个可选字段加五个顺序随意的必填项,每种组合都编码成类型会膨胀得没法看,一个 build(self) -> Result 更好维护。类型系统能表达,不等于值得表达。

多个 impl 块是组织工具,也是条件能力

一个类型可以有多个固有 impl 块,它们只是把方法分开放。小类型没必要拆;类型大了,可以按职责分组。泛型类型还能让某些方法只在满足条件时才存在:

rust
struct Batch<T>(Vec<T>);
 
impl<T> Batch<T> {
    fn len(&self) -> usize {
        self.0.len()
    }
}
 
impl<T: Ord> Batch<T> {
    fn max(&self) -> Option<&T> {
        self.0.iter().max()
    }
}

Batch(vec![12, 80, 3]) 有 len 也有 max,输出 3 Some(80)。换成 Batch(vec![0.5, 1.5]),len 照常可用,max 就不在候选里了:

text
error[E0599]: the method `max` exists for struct `Batch<{float}>`, but its trait bounds were not satisfied
  --> main.rs:20:29
   |
20 |     println!("{:?}", ratios.max());
   |                             ^^^ method cannot be called on `Batch<{float}>` due to unsatisfied trait bounds
   |
note: trait bound `{float}: Ord` was not satisfied

原因是浮点没有 Ord(NaN 没法比,第 3 章讲过)。能力跟着类型条件出现,调用者不必在运行时问“这个袋子能不能求最大值”。拆分块应当服务于稳定的边界,例如“所有 T 都有的基础操作”和“T: Ord 才有的排序操作”,不必每个方法单独占一个块。

trait:定义、实现与默认方法

固有方法只能由定义类型的 crate 添加。trait 先声明一份能力,再让类型各自实现。定义时给出方法签名,可以顺手给默认实现;实现者只需要补没有默认的部分,也可以覆盖默认的:

rust
trait Describe {
    fn label(&self) -> String;
 
    fn describe(&self) -> String {
        format!("<{}>", self.label())
    }
}
 
impl Describe for Level {
    fn label(&self) -> String {
        match self {
            Level::Ok => "ok".to_string(),
            Level::ClientError => "client".to_string(),
        }
    }
}
 
impl Describe for Status {
    fn label(&self) -> String {
        format!("status {}", self.0)
    }
 
    fn describe(&self) -> String {
        format!("[{}]", self.0)
    }
}

(这里的 Level 和 Status 是本节自带的简化版,派生了 Clone, Copy。)Level 沿用默认的 describe,Status 自己覆盖,调用 Level::Ok.describe() 得到 <ok>,Status(404).describe() 得到 [404]。默认实现只能用 trait 里已有的方法,不能碰实现类型的字段,也不继承任何状态。trait 同时是契约:编译器只能核对签名一致,核对不了语义一致,空切片返回 None 还是 0.0,要靠文档和测试守住。

扩展方法,以及 trait 必须在作用域里

trait 还能给别人的类型加方法。下面给 [u32] 加一个统计平均延迟的方法:

rust
trait LatencyStats {
    fn mean(&self) -> Option<f64>;
}
 
impl LatencyStats for [u32] {
    fn mean(&self) -> Option<f64> {
        if self.is_empty() {
            return None;
        }
        let sum: u64 = self.iter().map(|&n| u64::from(n)).sum();
        Some(sum as f64 / self.len() as f64)
    }
}
 
fn main() {
    let latencies = [12, 80, 3];
    println!("{:?} {:?}", latencies.mean(), [0u32; 0].mean());
}
text
Some(31.666666666666668) None

数组借着自动转换找到了切片上的实现。如果 trait 定义在别的模块,调用处必须 use 它:点号不会在所有依赖里搜索扩展方法,免得不同库往同一个类型上悄悄塞同名方法。

blanket impl 与它占住的位置

可以一次给“满足某个约束的所有类型”实现 trait,这叫通用实现(blanket impl):

rust
trait Loud {
    fn loud(&self) -> String;
}
 
impl<T: Describe> Loud for T {
    fn loud(&self) -> String {
        self.describe().to_uppercase()
    }
}

所有实现了 Describe 的类型都有了 loud,Level::ClientError.loud() 得到 <CLIENT>。便利的代价是占位:你不能再给具体的 Level 写另一份重叠的实现。

text
error[E0119]: conflicting implementations of trait `Loud` for type `Level`
  --> main.rs:20:1
   |
7  | impl<T: Describe> Loud for T {
   | ---------------------------- first implementation here
...
20 | impl Loud for Level {
   | ^^^^^^^^^^^^^^^^^^^ conflicting implementation for `Level`

库在发布 blanket impl 之前要想清楚,它会限制所有下游以后能写什么。

静态分发与 trait 对象

约束写在泛型参数上时,编译器针对每个实际类型各生成一份代码,调用在编译期就定了,这是静态分发(static dispatch);要把不同类型放进同一个集合,得用 trait 对象(trait object,dyn Trait),调用在运行时按实际类型分发,这是动态分发(dynamic dispatch):

rust
fn show_static<T: Describe>(item: &T) {
    println!("{}", item.describe());
}
 
fn show_all(items: &[Box<dyn Describe>]) {
    for item in items {
        println!("{}", item.describe());
    }
}
 
fn main() {
    show_static(&Level::Ok);
    show_static(&Status(404));
    show_all(&[Box::new(Level::ClientError), Box::new(Status(500))]);
}
text
<ok>
[404]
<client>
[500]

Box 是堆上的智能指针,第 10 章讲;这里只要知道 Box<dyn Describe> 是“指向某个实现了 Describe 的值”,不同类型的值因此能进同一个切片。静态分发没有运行时开销,代码量随类型数量增长;动态分发每次调用多一次间接,换来异构集合和更小的二进制。能在编译期确定类型就用泛型,需要在运行时挑类型,或者把一堆不同类型放在一起,再考虑 dyn。

trait 对象要求 trait “对象安全”:被动态调用的方法不能带类型参数,也不能在接收者以外使用 Self。返回 Self 的方法可以加 where Self: Sized 把自己排除在对象之外,trait 其余部分仍可动态使用。不用为“也许以后要动态分发”把所有 trait 都削成对象安全的,但核心用途就是异构集合时,设计之初就要验证。

泛型代码只能依赖约束里写出来的能力,约束怎么读、where 怎么写,第 5 章已经讲过,这里不重复。一条补充:约束就按函数体真正用到的能力写,别多要 Clone + Send + Sync + 'static 这种用不上的,权限越小,越容易组合。

孤儿规则与 newtype

想让 Vec<Status> 直接支持 {} 打印,很自然会这样写:

rust
use std::fmt;
 
impl fmt::Display for Vec<Status> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}", self.len())
    }
}

(Display 是标准库里管“给人看的文本格式”的 trait,第 7 章讲;这里只看它是外部的。)

text
error[E0117]: only traits defined in the current crate can be implemented for types defined outside of the crate
 --> main.rs:6:1
  |
6 | impl fmt::Display for Vec<Status> {
  | ^^^^^^^^^^^^^^^^^^^^^^-----------
  | |                     |
  | |                     `Vec` is not defined in the current crate
  | impl doesn't use only types from inside the current crate
  |
  = note: define and implement a trait or new type instead

Display 和 Vec 都不是本 crate 的,这违反孤儿规则(orphan rule):trait 和类型至少要有一个是本地的。第一次撞上很像编译器多管闲事,放大到整个生态就明白了:两个依赖库都为 Vec<Status> 实现 Display,格式还不一样,你同时引入它们该听谁的?某个依赖升级后新增了这份实现,原本能编译的下游会突然冲突。孤儿规则提前消除了这类跨 crate 争夺。

孤儿规则四象限:trait 和类型只要有一个是本地的就允许,两个都是外部的则拒绝,出路是 newtype 包装

三个象限允许,两个都在外部时拒绝,newtype 把类型变成本地的。

只想加方法,定义本地 trait 就行,前面的 LatencyStats 就是这样绕过的。需要给外部类型换一个新身份、再实现外部 trait,就要用 newtype:

rust
struct StatusList(Vec<Status>);
 
impl fmt::Display for StatusList {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let codes: Vec<String> = self.0.iter().map(|s| s.0.to_string()).collect();
        write!(f, "{}", codes.join(","))
    }
}

println!("{}", StatusList(vec![Status(200), Status(404), Status(503)])) 输出 200,404,503。StatusList 是本地类型,可以实现任何 trait;运行时它仍是同一份数据,类型系统却认为它是新类型,也就不会让人把任意 Vec<Status> 误传给只接受状态列表的接口。代价是需要自己决定暴露哪些容器能力,必要时补 From、迭代器之类的转换。

有人会立刻给 newtype 实现 Deref<Target = Vec<Status>>,让所有 Vec 方法直接可用。对真正像智能指针的类型这很自然;对有领域含义的包装类型,它会把修改入口全开放出去,守好的不变式又失守,还增加了方法重名的机会。多写一个 as_slice 和一个受控的 push,边界保留得更清楚。Deref 本身第 10 章再讲。

enum 的方法把 match 收回类型内部

impl 不只属于结构体。第 2 章的 Level 可以把“这一档叫什么、算不算错误”收进自己的方法里:

rust
impl Level {
    pub fn label(self) -> &'static str {
        match self {
            Level::Ok => "ok",
            Level::ClientError => "client",
            Level::ServerError => "server",
        }
    }
 
    pub fn is_error(self) -> bool {
        !matches!(self, Level::Ok)
    }
}

Level 是 Copy,所以接收者直接写 self。同一个判断以前散在各处的 match 里,现在只有一份;将来新增一档,编译器会在 label 里提醒你补分支。Status::level 又把状态码映射到 Level,调用者写 entry.status().level().label() 就够了,不必再记 100 到 399 算哪一档。

别为了藏起 match 而藏。调用者如果本来就要为每个变体做完全不同的事,硬塞一堆模糊的布尔方法反而丢信息;match 本身不是坏味道,同一个业务判断复制了好几份才是。

点号背后的自动借用与解引用

text.push_str(" API") 需要 &mut String,调用处没写 &mut;text.len() 需要 &String,也没写 &。点号调用会根据候选接收者类型,尝试补上借用。自动解引用让包装类型也更顺手:

rust
let line = Box::new(String::from("  alice /home 200 12  "));
println!("{} {}", line.len(), line.trim());
text
22 alice /home 200 12

Box<String> 能解引用成 String,String 又能解引用成 str,len 和 trim 分别在不同的层上找到。这不是继承,也没有把底层类型的方法复制一份:方法查找时,编译器按下面的步骤构造一串候选接收者。

方法查找:Box 包着 String、String、str 三层,每层依次试 T、&T、&mut T,在 str 层的 &T 上命中

从接收者的类型出发,每解引用一层就多一组候选。

第 1 步

从接收者表达式的类型开始,沿着可用的解引用关系反复展开候选类型;末端还可能尝试数组到切片这类转换。

第 2 步

对每个候选类型,依次把它本身、它的共享引用、它的可变引用放进候选序列。所以一个表面上的“值调用”,可能匹配接收 self、&self 或 &mut self 的方法。

第 3 步

按候选的顺序检查可见的固有方法和 trait 方法。找到多个无法区分的目标时,编译器要求你写得更明确;找到之后若不满足可变性或生命周期要求,照样报错。

在显微镜里点“开始查找”,逐层展开候选接收者;页面里的冲突标本需要完全限定语法才能消歧,下一节会讲。

这个过程里最容易想错的是顺序:查找沿着候选接收者往下走,不是先把全世界的固有方法收齐、排在所有 trait 方法前面。较早候选上的 trait 方法,可能比较晚候选上的固有方法先被选中:

rust
impl Probe {
    fn inspect(&mut self) -> &'static str { "固有方法" }
}
 
impl Inspect for Probe {
    fn inspect(&self) -> &'static str { "trait 方法" }
}
 
fn main() {
    let mut probe = Probe;
    println!("{}", probe.inspect());
    println!("{}", Probe::inspect(&mut probe));
}
text
trait 方法
固有方法

第一次点号调用先试到的是 &Probe 这一格,那里只有 trait 版本;第二次写 Probe::inspect(&mut probe),明确选了固有版本。这个例子在真实代码里很少出现,它要纠正的是一个危险的口诀:“有同名固有方法,就一定调用固有方法。”靠接收者可变性来区分两个同名方法,只会让读者吃惊,直接换名字。

Deref 会扩大公开 API:实现之后,目标类型的方法也进了查找范围,目标类型将来新增的方法还可能和你的同名;调用者也会自然把包装值当成“就是一种目标值”。只有解引用便宜、不会失败、透明的行为符合直觉时才实现它,只想提供一次明确转换,AsRef 或 as_str 这样的方法边界更清楚。

自动借用不会替你绕开借用规则。绑定没有声明 mut,点号不能凭空取得可变引用;共享引用仍在使用,它也不会替你提前结束。语法糖只省符号,不减检查。

完全限定语法:重名时把意图写全

两个 trait 都给同一个类型提供同名方法时,点号就无法决定:

rust
impl Text for Report { /* render, media_type */ }
impl Json for Report { /* render, media_type */ }
 
let report = Report;
println!("{}", report.render());
text
error[E0034]: multiple applicable items in scope
  --> main.rs:20:27
   |
20 |     println!("{}", report.render());
   |                           ^^^^^^ multiple `render` found
   |
note: candidate #1 is defined in an impl of the trait `Json` for the type `Report`
note: candidate #2 is defined in an impl of the trait `Text` for the type `Report`
help: disambiguate the method for candidate #1
   |
20 |     println!("{}", Json::render(&report));

按 help 的提示指定 trait 就行。方法有 self,实参能推断出实现类型,Json::render(&report) 已足够;信息最完整、在泛型和重名场景里最稳的写法是完全限定语法(fully qualified syntax):<Report as Json>::render(&report),尖括号里写“把 Report 当作 Json 的实现”。没有 self 的关联函数没有实参帮着推断,更需要它:

text
error[E0790]: cannot call associated function on trait without specifying the corresponding `impl` type
 --> main.rs:9:20
  |
9 |     println!("{}", Text::media_type());
  |                    ^^^^^^^^^^^^^^^^^^ cannot call associated function of trait
  |
help: use the fully-qualified path to the only available implementation
  |
9 |     println!("{}", <Report as Text>::media_type());

同样,Report::media_type() 在两个 trait 都实现了它时会得到 E0034,必须写 <Report as Text>::media_type()。这里我不建议去背一张优先级表:自动借用、自动解引用、泛型约束和 trait 是否在作用域里,都会改变候选集合。遇到两个 trait 重名、固有方法与 trait 方法接收者形式不同、智能指针和它指向的值都有同名方法这些情形,直接写完全限定,比猜解析顺序可靠。多写十几个字符,换来的是原本藏在编译器查找过程里的选择,现在写在了代码表面。

公共方法一旦发布就会参与兼容性

在自己的应用里改签名,跟着编译器修完调用点就行。公共库的 impl 不同:接收者、返回值、约束和名字都会进入下游代码。

  • 改接收者不只是性能调整。name(&self) -> &str 改成 name(self) -> String,旧调用者取了名字之后继续用对象的代码都会断;&self 改成 &mut self 同样会破坏放在 Arc 后面或同时存在其他引用的调用。拿不准时先给最小权限,日后新增一个更强的方法,比收紧现有的容易。保留 body(&self) 和 into_body(self) 两个入口不算重复,一个临时观察,一个转移所有权,名字已经把区别说清了。
  • 新增固有方法可能改变旧的点号调用的目标。下游一直通过扩展 trait 调用 value.format(),你新增一个同名固有方法,旧代码的行为就可能变。Deref 包装类型风险更大,因为目标类型将来新增的方法也会进入候选。通用类型少放模糊的短名字,扩展 trait 用更有领域信息的名字。
  • 返回具体借用会限制将来的存储方式。fn name(&self) -> &str 高效,也承诺结果直接借自 self;以后名字要按需计算或拼接,就返回不了普通 &str 了。这不意味着一律返回 String,给不确定的未来每次都分配同样有成本。稳定存储的文本直接返回 &str,确实可能借用也可能拥有的,考虑 Cow(标准库里“借用或拥有”的枚举,本课不展开)。
  • trait 新增有默认实现的方法,比新增必需方法温和;blanket impl 更要慎重,它可能和下游已有或计划中的实现重叠。

把接收者设计成调用者能读懂的协议

用“草稿消息”做一次接口评审:可以设置收件人和正文,发送前要校验,发送后草稿不该再被使用。第一版可能把所有方法都写成 &mut self:

rust
impl Draft {
    fn set_to(&mut self, to: String);
    fn set_body(&mut self, body: String);
    fn send(&mut self);
}

它能改数据,却没说清三件事:空收件人合不合法,发送会不会失败,为什么发送之后还能再调一次 send。重新设计的签名读起来就是一份协议:

rust
impl Draft {
    fn new() -> Self;
    fn to(self, recipient: impl Into<String>) -> Self;
    fn body(self, body: impl Into<String>) -> Self;
    fn preview(&self) -> &str;
    fn build(self) -> Result<Message, DraftError>;
}
 
impl Message {
    fn recipient(&self) -> &str;
    fn send(self) -> Result<String, String>;
}

preview(&self) 允许反复查看;配置方法 self -> Self 形成一次性的构建链;build(self) 消费草稿并检查不变式;send(self) 消费合法消息,同一个 Message 值不会被发送两次。注意措辞的分寸:编译器保证的只是内存里的这个值不能再被普通安全代码使用,不保证外部系统绝不重复投递,进程可能重试,请求可能超时。

编译器能保证什么、不能保证什么,要诚实:self 能阻止当前值再次使用,拦不住调用者提前克隆一份;&mut self 保证本进程安全 Rust 代码里的独占,锁不住数据库里的同一行;私有字段收紧创建入口,代替不了外部输入校验;Result 逼调用者面对失败分支,拦不住他直接 unwrap。让类型系统承担它擅长的局部保证,系统级的问题交给幂等键、数据库约束和测试。

常见借用报错,怎样倒推接口

方法写完遇到借用错误,先别急着把返回值全改成克隆。先看编译器指出的两次访问分别想做什么,再决定是缩短借用、拆分字段还是改接口。

返回引用之后又要修改对象,和第 4 章的 first 加 push 是同一件事(Vec 扩容可能搬走缓冲区,旧引用真会悬空),修法见前面 Tally 的两条:用完再改,或者拿拥有的副本。

另一类是一次方法借用了整个 self。字段互不相关,编译器在直接访问字段时能看出来,一旦跨过方法边界,它只看签名,签名授予的是整个 self:

rust
let users = t.users_mut();
let paths = t.paths_mut();
users.push("alice".to_string());
text
error[E0499]: cannot borrow `t` as mutable more than once at a time
  --> main.rs:15:17
   |
14 |     let users = t.users_mut();
   |                 - first mutable borrow occurs here
15 |     let paths = t.paths_mut();
   |                 ^ second mutable borrow occurs here
16 |     users.push("alice".to_string());
   |     ----- first borrow later used here

操作确实要同时改两个字段,就提供一次性拆开借用的方法:fn both_mut(&mut self) -> (&mut Vec<String>, &mut Vec<String>),函数体里写 (&mut self.users, &mut self.paths),编译器能看见这是两个不同字段的两份引用(这一版我也真跑过,通过)。另一条路是把字段提炼成各自的子结构,让方法只借用需要的部分。这时别急着用 RefCell 绕过去,报错多半在提醒你的类型承担了互不相干的职责。

还有一类:循环里反复调用 batch.finish()(finish(self)),第一次就把 batch 移走了。“完成”如果本来只该发生一次,那循环才是错的;只想反复查长度,就该是 len(&self);需要失败后重试,让错误把原值带回来,比如 Result<Output, (Self, Error)>。顺着报错倒推业务语义,往往比随手加 clone() 更接近正确的设计。

回到 logbook:v0.6

第 5 章留下的缺口现在补上:Status 守住 100 到 599,LogEntry 字段私有、只能 parse,Level 有了自己的方法,ReportBuilder 消费自己产出 Report。完整程序如下,HashSet、BTreeMap 来自第 4 章,iter().max_by_key 属于第 8 章,先照抄:

rust
mod logbook {
    use std::collections::{BTreeMap, HashSet};
    use std::num::ParseIntError;
 
    #[derive(Debug)]
    pub enum ParseError {
        MissingField(&'static str),
        BadNumber {
            field: &'static str,
            source: ParseIntError,
        },
        StatusOutOfRange(u16),
    }
 
    #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
    pub struct Status(u16);
 
    #[derive(Debug, Clone, Copy, PartialEq, Eq)]
    pub enum Level {
        Ok,
        ClientError,
        ServerError,
    }
 
    impl TryFrom<u16> for Status {
        type Error = ParseError;
 
        fn try_from(code: u16) -> Result<Self, Self::Error> {
            if (100..=599).contains(&code) {
                Ok(Status(code))
            } else {
                Err(ParseError::StatusOutOfRange(code))
            }
        }
    }
 
    impl Status {
        pub fn code(self) -> u16 {
            self.0
        }
 
        pub fn level(self) -> Level {
            match self.0 {
                100..=399 => Level::Ok,
                400..=499 => Level::ClientError,
                _ => Level::ServerError,
            }
        }
    }
 
    impl Level {
        pub fn label(self) -> &'static str {
            match self {
                Level::Ok => "ok",
                Level::ClientError => "client",
                Level::ServerError => "server",
            }
        }
 
        pub fn is_error(self) -> bool {
            !matches!(self, Level::Ok)
        }
    }
 
    #[derive(Debug, Clone)]
    pub struct LogEntry {
        user: String,
        path: String,
        status: Status,
        latency_ms: u32,
    }
 
    fn field(line: &str, n: usize) -> Option<&str> {
        line.split_whitespace().nth(n)
    }
 
    fn number<T: std::str::FromStr<Err = ParseIntError>>(
        line: &str,
        n: usize,
        name: &'static str,
    ) -> Result<T, ParseError> {
        let raw = field(line, n).ok_or(ParseError::MissingField(name))?;
        raw.parse()
            .map_err(|source| ParseError::BadNumber { field: name, source })
    }
 
    impl LogEntry {
        pub fn parse(line: &str) -> Result<LogEntry, ParseError> {
            let user = field(line, 0).ok_or(ParseError::MissingField("user"))?;
            let path = field(line, 1).ok_or(ParseError::MissingField("path"))?;
            let status = Status::try_from(number::<u16>(line, 2, "status")?)?;
            let latency_ms = number(line, 3, "latency_ms")?;
            Ok(LogEntry {
                user: user.to_string(),
                path: path.to_string(),
                status,
                latency_ms,
            })
        }
 
        pub fn user(&self) -> &str {
            &self.user
        }
 
        pub fn path(&self) -> &str {
            &self.path
        }
 
        pub fn status(&self) -> Status {
            self.status
        }
 
        pub fn latency_ms(&self) -> u32 {
            self.latency_ms
        }
 
        pub fn is_slow(&self, slow_ms: u64) -> bool {
            u64::from(self.latency_ms) >= slow_ms
        }
 
        pub fn into_user(self) -> String {
            self.user
        }
    }
 
    #[derive(Debug, PartialEq, Eq)]
    pub enum BuildError {
        ZeroTop,
        SlowMsOutOfRange(u64),
    }
 
    pub struct ReportBuilder {
        top: usize,
        slow_ms: u64,
    }
 
    pub struct Report {
        top: usize,
        slow_ms: u64,
    }
 
    impl ReportBuilder {
        pub fn new() -> Self {
            ReportBuilder { top: 5, slow_ms: 80 }
        }
 
        pub fn top(mut self, top: usize) -> Self {
            self.top = top;
            self
        }
 
        pub fn slow_ms(mut self, slow_ms: u64) -> Self {
            self.slow_ms = slow_ms;
            self
        }
 
        pub fn build(self) -> Result<Report, BuildError> {
            if self.top == 0 {
                return Err(BuildError::ZeroTop);
            }
            if !(1..=60_000).contains(&self.slow_ms) {
                return Err(BuildError::SlowMsOutOfRange(self.slow_ms));
            }
            Ok(Report { top: self.top, slow_ms: self.slow_ms })
        }
    }
 
    impl Report {
        pub fn render(&self, entries: &[LogEntry]) -> String {
            let mut users: HashSet<&str> = HashSet::new();
            let mut by_status: BTreeMap<Status, usize> = BTreeMap::new();
            let mut total_ms: u64 = 0;
            let mut slow: Vec<&LogEntry> = Vec::new();
            for e in entries {
                users.insert(e.user());
                *by_status.entry(e.status()).or_insert(0) += 1;
                total_ms += u64::from(e.latency_ms());
                if e.is_slow(self.slow_ms) {
                    slow.push(e);
                }
            }
            slow.sort_by(|a, b| b.latency_ms().cmp(&a.latency_ms()));
            slow.truncate(self.top);
 
            let mean = if entries.is_empty() {
                0.0
            } else {
                total_ms as f64 / entries.len() as f64
            };
            let mut out = String::new();
            out.push_str(&format!("total: {}\n", entries.len()));
            out.push_str(&format!("users: {}\n", users.len()));
            out.push_str(&format!("mean latency: {:.1} ms\n", mean));
            if let Some(e) = entries.iter().max_by_key(|e| e.latency_ms()) {
                out.push_str(&format!(
                    "slowest: {} {} {}ms\n",
                    e.user(),
                    e.path(),
                    e.latency_ms()
                ));
            }
            for (status, count) in &by_status {
                out.push_str(&format!("status {}: {}\n", status.code(), count));
            }
            out.push_str(&format!("slow requests (>= {} ms):\n", self.slow_ms));
            for e in slow {
                out.push_str(&format!(
                    "  {} {} {}ms [{}]\n",
                    e.user(),
                    e.path(),
                    e.latency_ms(),
                    e.status().level().label()
                ));
            }
            out
        }
    }
}
 
use logbook::{LogEntry, ReportBuilder, Status};
 
const SAMPLE: &str = "alice /home 200 12
bob /pay 500 80
alice /home 404 3
carol /api/orders 200 35
bob /pay 200 41
dave /login 401 7
alice /api/orders 503 120
carol /home 200 9";
 
fn main() {
    for line in ["erin /home abc 10", "frank /home 700 5", "gina /home", ""] {
        println!("{line:?} -> {:?}", LogEntry::parse(line).unwrap_err());
    }
    println!("{:?}", ReportBuilder::new().top(0).build().err());
    println!("{:?}", ReportBuilder::new().slow_ms(0).build().err());
    println!();
 
    let mut entries = Vec::new();
    for line in SAMPLE.lines() {
        entries.push(LogEntry::parse(line).expect("示例数据有效"));
    }
 
    let report = ReportBuilder::new()
        .top(5)
        .slow_ms(80)
        .build()
        .expect("设置有效");
    print!("{}", report.render(&entries));
 
    let level = Status::try_from(404).unwrap().level();
    println!("404 是 {},算错误:{}", level.label(), level.is_error());
    let first = entries.remove(0);
    println!("归档 {}", first.into_user());
}
text
"erin /home abc 10" -> BadNumber { field: "status", source: ParseIntError { kind: InvalidDigit } }
"frank /home 700 5" -> StatusOutOfRange(700)
"gina /home" -> MissingField("status")
"" -> MissingField("user")
Some(ZeroTop)
Some(SlowMsOutOfRange(0))
 
total: 8
users: 4
mean latency: 38.4 ms
slowest: alice /api/orders 120ms
status 200: 4
status 401: 1
status 404: 1
status 500: 1
status 503: 1
slow requests (>= 80 ms):
  alice /api/orders 120ms [server]
  bob /pay 80ms [server]
404 是 client,算错误:true
归档 alice

编译时会有几条 dead_code 警告,说 ParseError 的字段只被 Debug 读过,不影响运行。从 total: 起的九行就是全课固定的报表,后面多出的是 slow_ms = 80 时的慢请求清单(bob /pay 80 和 alice /api/orders 120,阈值含等号)。和 v0.5 比,有几处变化值得看:main 再也写不出 status: 999 的 LogEntry,唯一的出口是 parse;render 里的用户集合是 HashSet<&str>,不用像第 4 章那样克隆用户名,因为现在有了返回 &str 的 user(),借用在 entries 存活期间一直有效;report.render(&entries) 只借不拿,entries.remove(0) 取出的记录可以交给 into_user(self),名字一看就知道这条记录从此退场。Report 暂时没有实现 Display,所以用 render 返回 String,拼接也只能靠 push_str(&format!(…)),第 7 章有更顺手的写法。

练习

先做四道测验,再做三道动手题。

第 1 题 · 单选题

要给 `LogEntry` 加一个方法,取走记录里的用户名 `String` 且不克隆,调用之后这条记录不再使用。接收者应当选哪个?

第 2 题 · 单选题

`Status` 只包一个 `u16` 并派生了 `Copy`,`fn code(self) -> u16` 被调用之后,调用者手里的 `status` 还能用吗?

第 3 题 · 多选题 · 选出所有正确项

在自己的 crate 里,下面哪些做法能合法地扩展 `Vec<Status>`?
已选 0 项

第 4 题 · 判断题

只要字段是私有的,同一个模块里的代码也不可能把 `LogEntry` 改成不合法的状态。

设计一个有不变式的百分比类型

实现 Percentage,内部值只能在 0..=100:字段不能由类型外部直接修改;try_new(u8) -> Result<Self, PercentageError> 拒绝大于 100 的值;get(&self) -> u8 返回数值;into_inner(self) -> u8 消费包装值并返回内部数值。

先自己想一想,再看一种实现

一种实现已经藏好了,准备好再点开

修复一次借用冲突

下面的代码为什么不能编译?给出一种不分配的修复,和一种拥有型的修复。

rust
let mut queue = Queue { items: vec![String::from("A")] };
 
let first = queue.first().unwrap();
queue.push("B");
println!("{first}");

其中 first(&self) -> Option<&str>,push(&mut self, item: impl Into<String>)。

先自己想一想,再看分析

分析已经藏好了,准备好再点开

为状态转换选择失败语义

给上传状态 Pending、Uploading、Completed、Failed 设计转换方法。先回答一个问题:complete 失败之后,调用者还需要原来的状态吗?

先自己想一想,再看分析

分析已经藏好了,准备好再点开

现在 logbook 的报表只活在内存里。真实的工具要读 sample.log、读标准输入,把结果写进文件或终端,这些地方出错是常态;有时连错误都不会出现,你写了 print!("文件名: "),紧接着去 read_line,终端上什么也没显示,程序像是卡住了。下一章从这个“提示语不出现”的现象讲起,让 logbook 真正接上文件和标准输入输出。