为什么 Rust 不可变引用可以调用 &mut self 方法?
在我的代码注释中:
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(())
}
Run Code Online (Sandbox Code Playgroud)
在 的文档中ChildStdin,您可以找到impl Write for &ChildStdin. 这是在 1.48 中添加的,因为根据原始问题,这些写入应该可以安全调用,这些写入应该可以安全调用:
\n\nWrite 的实现在幕后是 MT 安全的,可以实现类似于 [...] 的特征,并且有些已经实现了 [...]。\n但是,这些似乎是当前实现的范围。以下类型也可以执行相同的操作:
\n\n
\n- [...]
\n- ChildStdin \xe2\x80\x93 类似于 File 或 *Streams;
\n
和公关。
\n&mut ChildStdin值得注意的是,我们在任何时候都没有。相反,您创建一个对不可变引用a的可变引用&mut &ChildStdin。然后,这个可变引用被赋予write_all链接Write实现中的特征方法&ChildStdin特征方法。
虽然也有一个impl Write for ChildStdin(这需要一个&mut ChildStdin),但我们实际上并没有在这里使用它。