实现说明
函数 publish、main定义了示例的全部动作。
错误装在 Result 里往回传,迫使每个调用点显式决策。
使用要点
- 每个可能失败的调用都产出必须拆包或传播的
Result;没有隐式抛出。 - 每一步打印都带着自己的标签:
published:。 - 执行文件,
main会按顺序走完publish。
常见问题
错误怎么传到调用方?
通过类型系统:失败是 Result 的变体,调用方必须消费它。
运行「改名发布前先用 sync_all 落盘」会打印什么?
整个文件跑完,输出行以 published: 这类前缀开头。
签名一览:fn publish(dir: &Path, payload: &[u8]) -> std::io::Result<PathBuf>
核心语句
let live = publish(&dir, br#"{"retries": 3}"#)?;
fs::rename(&staged, &live)?; // 同一文件系统内改名原子生效
Ok(live)
}
fs::create_dir_all(&dir)?;
代码示例
use std::fs::{self, OpenOptions};
use std::io::Write;
use std::path::{Path, PathBuf};
// 写暂存文件 -> sync_all 落盘 -> 原子改名发布
fn publish(dir: &Path, payload: &[u8]) -> std::io::Result<PathBuf> {
let staged = dir.join("config.json.new");
let live = dir.join("config.json");
let mut file = OpenOptions::new()
.write(true)
.create(true)
.truncate(true)
.open(&staged)?;
file.write_all(payload)?;
file.sync_all()?; // 数据与元数据一起压到磁盘,再谈发布
fs::rename(&staged, &live)?; // 同一文件系统内改名原子生效
Ok(live)
}
fn main() -> std::io::Result<()> {
let dir = std::env::temp_dir().join("sync_all_demo");
fs::create_dir_all(&dir)?;
let live = publish(&dir, br#"{"retries": 3}"#)?;
println!("published: {}", fs::read_to_string(&live)?);
fs::remove_file(&live).ok();
fs::remove_dir_all(&dir).ok();
Ok(())
}