【问题标题】:Get mutable reference to element of Vec or create new element and get that reference [duplicate]获取对 Vec 元素的可变引用或创建新元素并获取该引用 [重复]
【发布时间】:2020-08-28 13:50:10
【问题描述】:

我有一个Vec<State> 列表,并且想要搜索一个元素并获得对其的可变引用。如果不存在,则应创建一个新的默认元素并将其添加到列表中:

struct State {
    a: usize,
}

fn print_states(states: &Vec<State>) {
    for state in states {
        print!("State{{a:{}}} ", state.a);
    }
    println!();
}

fn main() {
    let mut states = vec![State { a: 1 }, State { a: 2 }, State { a: 3 }];

    print_states(&states);

    let mut state = match states.iter_mut().find(|state| state.a == 2) {
        Some(state) => state,
        None => {
            let new_state = State { a: 3 };
            states.push(new_state);
            states.last().unwrap()
        }
    };
    state.a = 4;
    drop(state);
    print_states(&states);
}

这导致:

error[E0594]: cannot assign to `state.a` which is behind a `&` reference
  --> src/main.rs:25:5
   |
17 |     let mut state = match states.iter_mut().find(|state| state.a == 2) {
   |         --------- help: consider changing this to be a mutable reference: `&mut State`
...
25 |     state.a = 4;
   |     ^^^^^^^^^^^ `state` is a `&` reference, so the data it refers to cannot be written

问题在于None 路径。当使用 None =&gt; panic!() 而不创建这个新的默认元素时,我可以修改找到的元素

我需要进行哪些更改才能完成这项工作?

【问题讨论】:

    标签: rust reference mutable


    【解决方案1】:

    你的问题是state.last().unwrap()-line。 .last() on Vec 的方法.last() 返回一个&amp;State,这会导致编译器将state 的类型推断为&amp;State(可以将Some()-case 中的&amp;mut State 强制转换为) .这就是为什么你不能在第 28 行更改 state

    将行更改为state.last_mut().unwrap()state 将是&amp;mut State 而不是&amp;State。您的示例在此之后编译。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-10-12
      • 2020-03-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-03-27
      相关资源
      最近更新 更多