rust - 如果类型没有实现复制,我如何将具体类型与选项的Option进行比较?

标签 rust

在这种情况下获取错误"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/

相关文章:

pointers - 带有原始指针的静态结构给出 "` core::marker::Sync` 未实现...”

multithreading - 复制 `std::thread::spawn` 导致堆栈溢出

module - Rust 中的跨模块函数调用

rust - 在一组 &str 上使用 BTreeSet::range 时需要类型注释

xml - serde-xml-rs 反序列化 u8 有效但 u16 无效

visual-studio-code - 如何获取要显示的类型提示?

rust - 什么时候应该使用函数指针而不是闭包?

rust - 将C回调API转换为流

rust - 引用必须在 block 上定义的生命周期 'a 内有效

rust - 将 'borrow' 结构深深地移入其他对象的最佳方法是什么?