← 中文资源

简体中文版本

为计数 sink 实现 Write trait

为计数 sink 实现 Write trait:write 统计字节与换行数并如实报告消费长度,write! 与 write_all 走同一条路径。

阅读英文原文

实现说明

为计数 sink 实现 Write trait以函数 write、flush、main为骨架。 可能失败的操作返回 Result,? 运算符把错误短路传给调用方。

使用要点

  • 每个可能失败的调用都产出必须拆包或传播的 Result;没有隐式抛出。
  • 跑完文件,输出里会留下标记——bytes:、lines:。

常见问题

错误是如何上报的?

通过类型系统:失败是 Result 的变体,调用方必须消费它。

运行「为计数 sink 实现 Write trait」会打印什么?

不用做任何设置,直接把文件跑完——输出里的 bytes:、lines: 标签标明各步骤。

主要签名是 fn write(&mut self, buf: &[u8]) -> io::Result<usize>

核心语句

self.lines += buf.iter().filter(|&&b| b == b'\n').count() as u64;
sink.write_all(b"tail without newline")?;
fn flush(&mut self) -> io::Result<()> {
    Ok(())
}

代码示例

use std::io::{self, Write};

struct CountingSink {
    bytes: u64,
    lines: u64,
}

impl Write for CountingSink {
    fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
        self.bytes += buf.len() as u64;
        self.lines += buf.iter().filter(|&&b| b == b'\n').count() as u64;
        Ok(buf.len()) // 如实报告消费的字节数,write_all 依赖它决定是否重试
    }

    fn flush(&mut self) -> io::Result<()> {
        Ok(())
    }
}

fn main() -> io::Result<()> {
    let mut sink = CountingSink { bytes: 0, lines: 0 };
    write!(sink, "first metric\n")?;
    write!(sink, "second {}\n", "metric")?;
    sink.write_all(b"tail without newline")?;
    println!("bytes: {}", sink.bytes);
    println!("lines: {}", sink.lines);
    Ok(())
}