在这种情况下获取错误"use of moved value"
#[derive(PartialEq)]
struct Something {
name: String,
}
fn example() {
fn get_something_maybe() -> Option<Something> {
todo!()
}
fn do_with_something(thing: Something) {
todo!()
}
let maybe_something = get_something_maybe();
let concrete_something = Something {
name: "blah".to_string(),
};
// how can I compare a concrete something to a maybe of something easily?
if Some(concrete_something) != maybe_something {
// I just want to compare the concrete thing to an option of the thing which are themselves comparable
do_with_something(concrete_something);
}
}
warning: unused variable: `thing`
--> src/lib.rs:11:26
|
11 | fn do_with_something(thing: Something) {
| ^^^^^ help: if this is intentional, prefix it with an underscore: `_thing`
|
= note: `#[warn(unused_variables)]` on by default
error[E0382]: use of moved value: `concrete_something`
--> src/lib.rs:24:27
|
16 | let concrete_something = Something {
| ------------------ move occurs because `concrete_something` has type `Something`, which does not implement the `Copy` trait
...
22 | if Some(concrete_something) != maybe_something {
| ------------------ value moved here
23 | // I just want to compare the concrete thing to an option of the thing which are themselves comparable
24 | do_with_something(concrete_something);
| ^^^^^^^^^^^^^^^^^^ value used here after move
最佳答案
您可以将Option<&T>
而不是Option<T>
进行比较:
#[derive(PartialEq, Debug)]
struct Something {
name: String,
}
fn get_something_maybe() -> Option<Something> {
Some(Something {
name: "asdf".to_string(),
})
}
fn main() {
let maybe_something = get_something_maybe();
let concrete_something = Something {
name: "asdf".to_string(),
};
if Some(&concrete_something) == maybe_something.as_ref() {
println!("they're equal");
}
println!(
"neither has been moved: {:?} {:?}",
maybe_something, concrete_something
);
}
关于rust - 如果类型没有实现复制,我如何将具体类型与选项的Option进行比较?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64445399/