Why can I not call borrow_mut() after indexing into an immutable Vec?

后端 未结 2 1849
陌清茗
陌清茗 2020-12-18 03:25

Let\'s try to compile this code:

use std::cell::RefCell;

struct Foo {
    v: Vec>,
}

impl Foo {
    fn f(&self, i: usize) {
            


        
相关标签:
2条回答
  • 2020-12-18 03:55

    This is a known issue where IndexMut is sometimes selected when Index should actually be used.

    Your workaround of using {} is reasonable, but you can also use Index explicitly:

    use std::cell::RefCell;
    
    fn f(v: Vec<RefCell<u8>>) {
        use std::ops::Index;
        let _t = &mut v.index(0).borrow_mut();
    }
    
    fn main() {}
    

    See also:

    • Why does a mutable borrow of a closure through DerefMut not work?
    • How to use `BorrowMut` contained within `RefCell`?
    0 讨论(0)
  • 2020-12-18 04:14

    Another workaround is to explicitly call RefCell::borrow_mut(&v[0]).

    0 讨论(0)
提交回复
热议问题