← 中文资源

简体中文版本

用 io::Cursor 在内存里读写

io::Cursor 把 Vec<u8> 包装成可 Read/Seek/Write 的源:read_exact 按帧读取、SeekFrom 负偏移从尾部定位、position 跟踪进度,拼装字节全在内存完成,不落盘。

阅读英文原文

实现说明

用 io::Cursor 在内存里读写的核心是函数 main。

使用要点

  • 直接运行文件,输出会带上标签,比如 head:、tail:、position:——输出的每一行都能指回产生它的那次调用。

常见问题

运行「用 io::Cursor 在内存里读写」会打印什么?

运行文件本身,head:、tail:、position: 这些前缀各对应一段演示逻辑。

核心语句

cursor.read_to_string(&mut tail).unwrap();
cursor.seek(SeekFrom::End(-4)).unwrap();
cursor.read_exact(&mut head).unwrap();

代码示例

use std::io::{Cursor, Read, Seek, SeekFrom, Write};

fn main() {
    // Cursor 把内存字节当成可 Read/Seek 的源,不需要真实文件
    let mut cursor = Cursor::new(b"header,body,rows".to_vec());

    let mut head = [0u8; 6];
    cursor.read_exact(&mut head).unwrap();
    println!("head: {}", String::from_utf8_lossy(&head));

    // Seek 负偏移从尾部倒数
    cursor.seek(SeekFrom::End(-4)).unwrap();
    let mut tail = String::new();
    cursor.read_to_string(&mut tail).unwrap();
    println!("tail: {tail}");

    // position 跟踪读取进度
    println!("position: {}", cursor.position());

    // Cursor 同样是 Write 目标:字节直接写进内存
    let mut out = Cursor::new(Vec::new());
    out.write_all(b"packed").unwrap();
    println!("written: {}", String::from_utf8_lossy(&out.into_inner()));
}