gpt4 book ai didi

rust - 如何有条件地在结构的两个字段之间进行选择,然后更新所选字段?

转载 作者:行者123 更新时间:2023-11-29 08:29:34 24 4
gpt4 key购买 nike

我在一个较大的结构中有两个相同类型的结构。我将选择其中一个结构并使用相同的代码执行更新。

简化版:

#[derive(Debug)]
struct Counts {
value: u16,
count: u8,
}

#[derive(Debug)]
struct Partitioned {
even: Counts,
odd: Counts,
}

fn sort() -> Partitioned {
let mut even = Counts { value: 2, count: 0 };

let mut odd = Counts { value: 3, count: 0 };

for i in 1..30 {
let mut s = if i % 2 == 0 { even } else { odd };
s.count = s.count + 1;
// ... a lot of other code
}

Partitioned { even, odd }
}

fn main() {
println!("{:?}", sort());
}

这不包含关于所有权的投诉:

error[E0382]: use of moved value: `even`
--> src/main.rs:19:37
|
19 | let mut s = if i % 2 == 0 { even } else { odd };
| ^^^^ value moved here in previous iteration of loop
|
= note: move occurs because `even` has type `Counts`, which does not implement the `Copy` trait

error[E0382]: use of moved value: `odd`
--> src/main.rs:19:51
|
19 | let mut s = if i % 2 == 0 { even } else { odd };
| ^^^ value moved here in previous iteration of loop
|
= note: move occurs because `odd` has type `Counts`, which does not implement the `Copy` trait

error[E0382]: use of moved value: `even`
--> src/main.rs:24:19
|
19 | let mut s = if i % 2 == 0 { even } else { odd };
| ---- value moved here
...
24 | Partitioned { even, odd }
| ^^^^ value used here after move
|
= note: move occurs because `even` has type `Counts`, which does not implement the `Copy` trait

error[E0382]: use of moved value: `odd`
--> src/main.rs:24:25
|
19 | let mut s = if i % 2 == 0 { even } else { odd };
| --- value moved here
...
24 | Partitioned { even, odd }
| ^^^ value used here after move
|
= note: move occurs because `odd` has type `Counts`, which does not implement the `Copy` trait

这是怎么回事?如何在不将所有更新代码复制到 if 的两个 block 的情况下实现它?

最佳答案

a mutable reference到现场:

let mut s = if i % 2 == 0 { &mut even } else { &mut odd };

关于rust - 如何有条件地在结构的两个字段之间进行选择,然后更新所选字段?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50775770/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com