Obteniendo un error "use of moved value" en este caso

#[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
1
Avner Barr 20 oct. 2020 a las 15:41

1 respuesta

La mejor respuesta

Puede comparar con Option<&T> en lugar de 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
    );
}
3
Shepmaster 20 oct. 2020 a las 12:56