为什么可以在对File的不可变引用上实现Read? [英] Why is it possible to implement Read on an immutable reference to File?

查看:51
本文介绍了为什么可以在对File的不可变引用上实现Read?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果您签出Read 文档,大多数方法都接受&mut self.这是有道理的,因为从某项读取通常会更新内部偏移,因此下一次读取将返回不同的数据.但是,编译如下:

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);
}

该文件不可更改,但是肯定可以读取数据.对我来说,这似乎不正确. 有人指出,有一个impl<'a> Read for &'a File ,但是一个不变的实例似乎正在被突变的事实似乎仍然很奇怪.

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.

推荐答案

正如@kennytm指出的那样,a.read_to_end(vec)等同于Read::read_to_end(&mut a, vec),因此(&file).read_to_end(vec)扩展为Read::read_to_end(&mut &file, vec).在后一个表达式中,&file是类型为&File的新临时值.使用对表达式的可变引用(例如&mut 42)没有问题.这正是这里发生的情况.表达式是对不可变值的引用这一事实无关紧要,因为我们实际上无法通过&mut &T对该值进行突变.

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.

关于为什么我们不需要File可变的问题:File基本上只是一个新类型的文件描述符,即由OS管理的打开文件表的索引. read和朋友根本不会更改此描述符,这就是为什么File不需要突变的原因.当然会发生突变,但这是由操作系统在其自己的数据结构上完成的,而不是在用户土地的rust代码中完成的.

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.

这篇关于为什么可以在对File的不可变引用上实现Read?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆