本文介绍了可变地借用一个struct字段,而在关闭时借用另一个的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个包含两个字段的结构,我想使用另一个字段(不可变的借用)来修改一个字段(可变的借用),但是从借用检查器中得到了一个错误.
I have a struct containing two fields and I want to modify one field (mutable borrow) using another field (immutable borrow), but I get an error from the borrow checker.
例如,以下代码:
struct Struct {
field1: Vec<i32>,
field2: Vec<i32>,
}
fn main() {
let mut strct = Struct {
field1: vec![1, 2, 3],
field2: vec![2, 3, 4],
};
strct.field1.retain(|v| !strct.field2.contains(v));
println!("{:?}", strct.field1);
}
出现以下错误:
error[E0502]: cannot borrow `strct.field1` as mutable because it is also borrowed as immutable
--> src/main.rs:12:5
|
12 | strct.field1.retain(|v| !strct.field2.contains(v));
| ^^^^^^^^^^^^^------^---^^-----^^^^^^^^^^^^^^^^^^^^
| | | | |
| | | | first borrow occurs due to use of `strct` in closure
| | | immutable borrow occurs here
| | immutable borrow later used by call
| mutable borrow occurs here
Rust在闭包中使用另一字段更新一个字段的Rust方法是什么?
What are the Rust ways of updating one field using another from within a closure?
推荐答案
通常,借用检查器可以区分结构的不同字段,但这在闭包(lambda)中不起作用.
Usually the borrow checker can distinguish between the different fields of a structure, but this doesn't work within closures (lambdas).
相反,借用闭包之外的第二个字段:
Instead, borrow the second field outside the closure:
let field2 = &strct.field2;
strct.field1.retain(|v| !field2.contains(v));
这篇关于可变地借用一个struct字段,而在关闭时借用另一个的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!