gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 11:58:20 25 4
gpt4 key购买 nike

为什么 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 的文档中,您可以找到 impl Write for &ChildStdin .这是在 1.48 中添加的,因为根据 the original issue,这些写入操作被认为是安全的。 :

    The implementations of Write which are MT-safe under the covers can implement a trait along the lines of [...] and some already do [...].However, these appear to be the extent of the current implementations. The following types could also do the same:

    • [...]
    • ChildStdin – similar to File or *Streams;

    PR .

    值得注意的是,我们没有 &mut ChildStdin在任何时候。相反,您创建了一个对不可变引用的可变引用,一个 &mut &ChildStdin .然后将此可变引用提供给 write_all来自链接的 trait 方法 Write &ChildStdin 的实现.
    虽然有 impl Write for ChildStdin也是(需要一个 &mut ChildStdin ),我们实际上并不在这里使用它。

    关于rust - 为什么 Rust 不可变引用可以调用 &mut self 方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69335605/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com