我有以下struct
struct Employee {
id: u64,
name: String,
}
我正在使用以下代码对其进行序列化,然后将序列化的字节数组写入文件:
let emp = Employee {
id: 1546,
name: "abcd".to_string(),
};
let mut file = OpenOptions::new()
.read(true)
.write(true)
.create(true)
.open("hello.txt")
.unwrap();
let initial_buf = &bincode::serialize(&emp).unwrap();
println!("Initial Buf: {:?}", initial_buf);
file.write(&initial_buf);
file.write(&[b'\n']);
file.flush();
file.seek(SeekFrom::Start(0)).unwrap();
let mut final_buf: Vec<u8> = Vec::new();
let mut reader = BufReader::new(file);
reader.read_until(b'\n', &mut final_buf).unwrap();
println!("Final Buf: {:?}", final_buf);
我得到以下输出:
Initial Buf: [10, 6, 0, 0, 0, 0, 0, 0, 4, 0, 0, 0, 0, 0, 0, 0, 97, 98, 99, 100]
Final Buf: [10]