为什么一个Rust不可变引用可以调用&mut self方法?
在我的代码评论中:
- stdin的类型是&ChildStdin,为什么可以调用"&mut self"函数write_all?
- 为什么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(())
}
&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