rust - 获取对 Vec 元素的可变引用或创建新元素并获取该引用
问题描述
我有一个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 => panic!()
不创建这个新的默认元素的情况下使用时,我可以修改找到的元素
我需要改变什么才能使这项工作?
解决方案
你的问题是state.last().unwrap()
-line。.last()
on方法Vec
返回 a &State
,这会导致编译器推断为的类型(state
可以将-case 中的 the 强制转换为)。这就是为什么你不能在第 28 行更改。&State
&mut State
Some()
state
将行更改为state.last_mut().unwrap()
andstate
将是 a&mut State
而不是&State
。您的示例在此之后编译。
推荐阅读
- php - Laravel 规则:基于两个请求输入的自定义验证
- c - 如何使用 fork() 在 C 中运行 3 个命令?
- html - Google reCAPTCHA v2:加载时遇到无效的“X-Frame-Options”标头
- jmeter - 当为 100 个线程执行 Jmeter 脚本时,Grafana 仪表板将“活动用户”显示为 1
- angular - 我应该为这个 Angular 组件编写哪些测试?
- amazon-web-services - 签名与 presignedUrl DigitalOCeane 上的错误不匹配
- javascript - 为什么我得到未捕获的类型错误属性值无法设置为未定义?
- javascript - 如何将 getter 值绑定到 HTML 中?
- java - 如何在服务器级别而不是在应用程序级别更改 Tomcat 的默认错误页面?
- python - 如何将嵌套的 json 展平为数据框 pandas