use std::error::Error;
use std::fs::File;
use std::io::{BufRead, BufReader};
fn main() ->Result<(),Box<dyn Error>> {
let path=r#"C:\Users\0\Downloads\123.txt"#;
let fd=File::open(path)?;
let fd_p=&fd;
let mut br=BufReader::new(fd_p);
let mut line=String::new();
br.read_line(&mut line)?;
println!("{}",line);
Ok(())
}
以上代码,BufReader::new(fd_p); 可以传入 fd_p 也可以传入 fd 都正常工作,感觉读取文件要改变数据才可以读取吧,比如文件指针位置,这个不可变引用 fd_p 读取是怎么做到的
1
Kaleidopink 1 天前
翻一下文档就能发现实现 Read trait 的是 &File, 而不是 File, 所以即便是不可变引用也可以读取. 内部实现则是用了 unsafe.
|
2
bli22ard OP @Kaleidopink File 也有实现 Read trait , 不过实现方式还是用 &File 的实现。 这些其实不是重点,重点是, 为什么读取数据可以是不可变的
|
3
nebkad 1 天前
@bli22ard #2
https://doc.rust-lang.org/stable/std/fs/struct.File.html Note that, although read and write methods require a &mut File, because of the interfaces for Read and Write, the holder of a &File can still modify the file, either through methods that take &File or by retrieving the underlying OS object and modifying the file that way. Additionally, many operating systems allow concurrent modification of files by different processes. Avoid assuming that holding a &File means that the file will not change. |
5
zizon 21 小时 12 分钟前
也容易理解吧.实际 fd 的状态是 os 维护的,rust 顶多是个上层 API 调用方.
|
6
nebkad 16 小时 47 分钟前
@bli22ard 如果你对 std 的设计不是很满意,你的 OS 平台支持你在 Rust 中使用 &mut 语义的话,你自己重新包装一个 File 也不是很难啊
|