实现说明
File Try Clone 共享偏移以函数 main为骨架。
Result 返回类型让两种结果都写进了签名。
使用要点
?运算符是承重墙:删掉一个,错误处理就变成你的事。- 直接运行文件,输出会带上标签,比如
first read:、second read:——输出的每一行都能指回产生它的那次调用。
常见问题
示例失败时会 panic 吗?
没有 panic——Result 携带失败,? 把它转发给调用方。
运行「File Try Clone 共享偏移」会打印什么?
不用做任何设置,直接把文件跑完——输出里的 first read:、second read: 标签标明各步骤。
入口签名:fn main() -> std::io::Result<()>
核心语句
file.write_all(b"shared cursor demo")?;
let mut duplicate = file.try_clone()?;
let mut file = File::create(&path)?;
代码示例
use std::fs::File;
use std::io::{Read, Seek, SeekFrom, Write};
fn main() -> std::io::Result<()> {
let path = std::env::temp_dir().join("try_clone_shared_cursor.txt");
let mut file = File::create(&path)?;
file.write_all(b"shared cursor demo")?;
file.seek(SeekFrom::Start(0))?;
// try_clone duplicates the handle, and both share one file cursor
let mut duplicate = file.try_clone()?;
let mut first = [0_u8; 6];
file.read_exact(&mut first)?;
println!("first read: {:?}", String::from_utf8_lossy(&first));
// the duplicate continues from the same offset, not from byte zero
let mut second = [0_u8; 6];
duplicate.read_exact(&mut second)?;
println!("second read: {:?}", String::from_utf8_lossy(&second));
let _ = std::fs::remove_file(&path);
Ok(())
}