rust - 为什么 `&mut &foo` 有效但 `&mut a_ref_to_foo` 无效?

标签 rust

在下面的示例中,t1 编译但 t2 不编译。

&mut &stream有什么特别之处吗?我认为 Deref 不会起作用。

use std::net::TcpStream;

fn t1() {
    let stream = TcpStream::connect("127.0.0.1").unwrap();
    let a = &mut &stream;
}

fn t2(stream: &TcpStream) {
    let a = &mut stream;
}

Playground

9  | fn t2(stream: &TcpStream) {
   |       ------ use `mut stream` here to make mutable
10 |     let a = &mut stream;
   |                  ^^^^^^ cannot borrow mutably

最佳答案

&mut &foo

这做了两件事 - 它创建了一个类型为 &Foo 的临时值,然后创建了另一个类型为 &mut &Foo 的临时值。

let a_ref_to_foo = &foo;
&mut a_ref_to_foo

这也创建了一个 &mut &Foo 类型的临时变量,但是通过变量绑定(bind) a_ref_to_foo 可以观察到的东西,不是另一个临时变量。

问题和这个例子是一样的:

// Works
String::new().clear();

// Doesn't work
let s = String::new();
s.clear();

当您拥有一个临时值时,您就拥有它的所有权,包括将其视为可变的。一旦将其分配给绑定(bind),绑定(bind) 便拥有所有权,您必须指明是否允许对其进行更改。

关于rust - 为什么 `&mut &foo` 有效但 `&mut a_ref_to_foo` 无效?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44312652/

相关文章:

rust - 使用 bindgen 设置包含路径

rust - 如何在作为子进程运行的shell中执行命令?

rust - "pub use"和 "pub mod"之间的区别?

使用特征对象时,使用rust 具有特征绑定(bind)的泛型类型

rust - 如何使用本地未发布的箱子?

asynchronous - 如何将异步函数存储在结构中并从结构实例中调用它?

rust - 为什么需要用户输入的代码在 Rust Playground 中不起作用?

rust - 从 Option 借来的 RefMut 生命周期不够长 (Option<Rc<RefCell<Node>>>)

rust - Rust:错误[E0495]:由于关闭中的冲突要求,无法推断出适当的生命周期以自动引用

debugging - 如何查看导致编译错误的扩展宏代码?