【问题标题】:Is there a way to match options behind references in Rust?有没有办法匹配 Rust 中引用后面的选项?
【发布时间】:2023-02-14 01:03:34
【问题描述】:

如果我有一个类似于以下内容的结构:

struct Thing {
    opt: Option<Box<u32>>
}
fn main() {
    let thing = Thing{opt:Some(Box::new(5))};
    let pointer = &thing;
    match pointer.opt {
        None => println!("There is nothing"),
        Some(thing) => println!("There is a thing {}", thing)
    }
}

我收到一条错误消息:“无法将‘pointer.opt’作为共享引用后面的枚举变体‘Some’移出” 有人可以解释为什么会发生此错误以及可能的解决方法吗?

我正在处理的事情需要使用对其中具有类似选项的结构的引用。

【问题讨论】:

    标签: rust


    【解决方案1】:

    std::option::Option::as_ref() 正是针对这种情况:

    match pointer.opt.as_ref() {
        None => println!("There is nothing"),
        Some(thing) => println!("There is a thing {}", thing)
    }
    

    【讨论】:

    • match &amp;pointer.opt 完成同样的事情吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-02-21
    • 1970-01-01
    • 2020-11-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多