Why is indexing a mutable vector based on its len() considered simultaneous borrowing?

后端 未结 1 1544
你的背包
你的背包 2021-01-18 21:29

I know the general answer — You can only borrow mutably once or immutably many times, but not both. I want to know why this specific case is considered simultaneous borrowin

1条回答
  •  后悔当初
    2021-01-18 22:23

    If so, surely the compiler could improve this...right?

    Indeed, NLL intentionally started conservatively, as explained in #494341.

    Extracting the temporary allows it to compile:

    fn main() {
        let mut v = vec![1, 2, 3, 4, 5];
        let n = 3;
        // checks on n and v.len() and whatever else...
        let s = v[..n].to_vec();
        for i in 0..n {
            let index = i + v.len() - n;
            v[index] = s[1];
        }
    }
    

    This makes it clear that the issue is strictly one of not computing the index before attempting to use it.

    Since it is not possible to start the call to IndexMut::index_mut(&mut self, index: Idx) before computing the Idx, there is no reason to start the mutable borrow of v before computing the index.

    1 Courtesy of trentcl.

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