How can I do a mutable borrow in a for loop?

此生再无相见时 提交于 2020-02-02 05:39:39

问题


I tried:

let mut vec = [1,2,3];

for mut x in &vec { *x=3; }
for mut &x in &vec { x=3; }
for mut *x in &vec { x=3; }
for mut x in mut &vec { *x=3; }
for mut x in &(mut vec) { *x=3; }

None of these work; how should I do it?


回答1:


You may want to re-read The Rust Programming Language section on mutability:

You can also create a reference to it, using &x, but if you want to use the reference to change it, you will need a mutable reference:

let mut x = 5;
let y = &mut x;
fn main() {
    let mut array = [1, 2, 3];

    for x in &mut array {
        *x = 3;
    }
}

See also:

  • What's the difference in `mut` before a variable name and after the `:`?

Note that your variable is not a vector. It is an array.



来源:https://stackoverflow.com/questions/39622783/how-can-i-do-a-mutable-borrow-in-a-for-loop

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