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

[亡魂溺海] 提交于 2019-12-01 18:58:33
Matthieu M.

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<Idx>::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.

1Courtesy of trentcl.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!