在文件中存储 i32 的本机、惯用且安全的方法是什么?

What is the native, idiomatic, and safe way to store an i32 in a file?

我正在寻找类似 i32(或任何有符号整数)的东西并将其存储在文件中。我知道 serde,但我希望了解如何以本地方式安全地完成此操作。

我想到的唯一解决方案是手动计算二进制并将其转换为 u8 数组。这是需要完成的方式吗?

调用to_be_bytes() or to_le_bytes()将其分别转换为大端或小端。

pub fn to_be_bytes(self) -> [u8; 4];
pub fn to_le_bytes(self) -> [u8; 4];

写下来:

use std::{fs::File, io::Write};

fn main() {
    let mut f = File::create("/tmp/myfile").expect("unable to open file");
    write!(&mut f, "{}", 42).expect("unable to write file");
}