为什么间接级别允许省略 `mut`?

Why does a level of indirection allow omitting `mut`?

为什么 write1 的参数不需要被 mut?它将值直接传递给另一个需要 mut 访问权限的函数。

write1 中需要 mut 的任何理由似乎都适用于 write2,但编译器不同意:

use std::io::Write;

fn main() {
    let out = &mut std::io::stdout();
    write1(out)
}

fn write1(mut out: impl Write) {      // `mut` not required. Adding `mut` produces warning: "variable does not need to be mutable"
    write2(out)
}

fn write2(mut out: impl Write) {  // `mut` required! Otherwise error "cannot borrow `out` as mutable, as it is not declared as mutable"
    writeln!(out, "hi").unwrap();
}

playground link

write1 中,您不是在变异 out,而是将它(移动)给 write2,就像 main 将它移动到write1.

write2 这样说可能更清楚:

fn write2(out: impl Write) {
    let mut out = out;
    writeln!(out, "hi").unwrap();
}

如果有参考文献,那就大不一样了。在这种情况下,正如您的直觉,您必须传播 mut:

fn main() {
    let mut out = &mut std::io::stdout();
    write1(&mut out)
}

fn write1(out: &mut impl Write) {
    write2(out)
}

fn write2(out: &mut impl Write) {
    writeln!(out, "hi").unwrap();
}