简体   繁体   English

如何将具体类型与具体类型的 Option 进行比较,该类型未实现 Copy?

[英]How do I compare a concrete type to an Option of the concrete type is the type does not implement Copy?

Getting an error "use of moved value" in this case在这种情况下出现错误"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

You can compare with Option<&T> instead of Option<T> :您可以与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
    );
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM