← 中文资源

简体中文版本

resize 与 fill 管理可复用缓冲

用 resize 与 fill 原地管理字节缓冲:扩容新槽位按 Clone 填充、截断直接丢弃尾部、复用前 fill 清掉上一次的脏数据。

阅读英文原文

实现说明

resize 与 fill 管理可复用缓冲以函数 main为骨架。

使用要点

  • 每一步打印都带着自己的标签:grown:、truncated:、reset:。

常见问题

运行「resize 与 fill 管理可复用缓冲」会打印什么?

整个文件跑完,输出行以 grown:、truncated:、reset: 这类前缀开头。

核心语句

let mut payload: Vec<u8> = (0..10).collect();

代码示例

fn main() {
    // resize grows: new slots are filled with clones of the fill value (growth requires T: Clone)
    let mut header = vec![0u8; 4];
    header.resize(8, 0xA5);
    println!("grown:     {header:02X?}");

    // resize truncates: extra elements are dropped outright, with no error
    let mut payload: Vec<u8> = (0..10).collect();
    payload.resize(6, 0);
    println!("truncated: {payload:02X?}");

    // fill resets the reusable buffer: clear the previous run's dirty data before reuse
    let mut scratch = vec![0xFFu8; 6];
    scratch.fill(0);
    println!("reset:     {scratch:02X?}");

    // fill can also target a range: the header is kept while the payload section resets uniformly
    let mut frame = vec![0u8; 10];
    frame[..2].copy_from_slice(&[0x1F, 0x2F]);
    frame[2..].fill(0xEE);
    println!("frame:     {frame:02X?}");
}