为什么Rust的不可变引用可以调用&mut self方法?

4

为什么一个Rust不可变引用可以调用&mut self方法?

在我的代码评论中:

  1. stdin的类型是&ChildStdin,为什么可以调用"&mut self"函数write_all?
  2. 为什么as_ref结果可以调用"&mut self"函数write_all?
use std::io::{self, Write};
use std::process::{Command, Stdio};

fn main() -> io::Result<()> {
    let child = Command::new("cmd.exe")
        .stdin(Stdio::piped())
        .stdout(Stdio::piped())
        .spawn()?;

    let mut stdin = child.stdin.as_ref().unwrap();
    
    //1. stdin's type is &ChildStdin, why can call a "&mut self" function write_all?
    stdin.write_all(b"dir\n")?;

    //2. and why as_ref result can call a "&mut self" function write_all?
    child.stdin.as_ref().unwrap().write_all(b"dir\n")?;
 
    let output = child.wait_with_output()?;

    println!("output = {:?}", output);

    Ok(())
}


3
原文:cause write is also implemented for &ChildStdin https://doc.rust-lang.org/std/process/struct.ChildStdin.html#impl-Write-1 so &mut self == &mut &ChildStdin翻译结果:因为&ChildStdin也实现了写入功能https://doc.rust-lang.org/std/process/struct.ChildStdin.html#impl-Write-1,所以`&mut self等同于&mut &ChildStdin`。 - Stargateur
1个回答

8
ChildStdin的文档中,可以找到&ChildStdinimpl Write。这是在1.48中添加的,因为根据原始问题,这些写入操作被认为是安全的可调用的:

在内部MT(Multiple Threads)安全的Write实现可以实现类似于[...]和一些已经做了[...]的trait。 然而,这些似乎是当前实现的全部,以下类型也可以做同样的事情:

  • [...]
  • ChildStdin——类似于File或*Streams;
并参见PR
值得注意的是,我们从未使用过&mut ChildStdin。相反,您创建了对不可变引用的可变引用,即&mut &ChildStdin。然后将此可变引用提供给来自链接的Write实现的write_all trait方法,以进行写入操作。
尽管也有一个impl Write for ChildStdin(需要&mut ChildStdin),但我们在此处实际上并未使用它。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接