< 返回版块

Easonzero 发表于 2023-02-13 19:33

use std::sync::Mutex;

struct N {
    a: i32,
    b: i32,
}

fn main() {
    let mut n = N { a: 0, b: 0 };
    let a = &n.a;
    let b = &mut n.b;
    println!("{a} {b}");// 编译正常

    // =============================

    let n = Mutex::new(N { a: 0, b: 0 });
    let mut n = n.lock().unwrap();

    let a = &n.a;
    let b = &mut n.b; // 编译失败
    println!("{a}, {b}");
}

评论区

写评论
4j3n 2023-02-14 23:06

https://rustcc.cn/article?id=dda99bbb-9651-42c9-86e8-3f1fb3e227fd

前几天也有人对RefCell::borrow_mut返回结果提出了同样的问题,可以参考下回复;

作者 Easonzero 2023-02-14 14:11
let n = &mut *n;

重新借用应该是个可行的方式

作者 Easonzero 2023-02-14 14:08

我懂了, 那么这种case有什么推荐做法么

--
👇
ctj12461: 因为 lock() 返回的实际上是 MutexGuard<T>,其实现了 DerefDerefMut

let a = &n.a;
let b = &mut n.b; // cannot borrow `n` as mutable, as it is not declared as mutable

这里的 ab都是自动解引用得来的,所以编译器分析时就发现先借用了 MutexGuard<T>,又可变借用了 MutexGuard<T>

ctj12461 2023-02-13 21:47

因为 lock() 返回的实际上是 MutexGuard<T>,其实现了 DerefDerefMut

let a = &n.a;
let b = &mut n.b; // cannot borrow `n` as mutable, as it is not declared as mutable

这里的 ab都是自动解引用得来的,所以编译器分析时就发现先借用了 MutexGuard<T>,又可变借用了 MutexGuard<T>

1 共 4 条评论, 1 页