Why is it possible to implement Read on an immutable reference to File?

让人想犯罪 __ 提交于 2019-11-26 17:24:25

问题


If you check out the docs for Read, most of the methods accept a &mut self. This makes sense, as reading from something usually updates an internal offset so the next read returns different data. However, this compiles:

use std::io::Read;
use std::fs::File;

fn main() {
    let file = File::open("/etc/hosts").unwrap();
    let vec = &mut Vec::new();
    (&file).read_to_end(vec).unwrap();
    println!("{:?}", vec);
}

The file isn't mutable, but the data is certainly being read in. This seems incorrect to me. It was pointed out that there is an impl<'a> Read for &'a File, but the fact that an immutable instance is seemingly being mutated still seems odd.


回答1:


As @kennytm pointed out, a.read_to_end(vec) is equivalent to Read::read_to_end(&mut a, vec), so (&file).read_to_end(vec) expands to Read::read_to_end(&mut &file, vec). In the latter expression, &file is a new temporary value of type &File. There is no problem with taking mutable references to an expression (e.g. &mut 42). This is exactly what happens here. The fact that the expression is a reference to an immutable value doesn't matter because we cannot actually mutate the value through a &mut &T.

Regarding the question why we don't need the File to be mutable: File is basically just a newtyped file descriptor, i.e. an index into an open-file table that is managed by the OS. read and friends will not change this descriptor at all, which is why the File does not need to be mutated. There is of course mutation going on, but that is done by the operating system on its own data structures and not in your user-land rust code.



来源:https://stackoverflow.com/questions/31503488/why-is-it-possible-to-implement-read-on-an-immutable-reference-to-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!