Rust中是否有一种方法可以匹配引用后面的选项?

huangapple go评论62阅读模式
英文:

Is there a way to match options behind references in Rust?

问题

I understand that you want a translation of the code without the code part itself. Here is the translated text:

"If I have a struct that is something along the lines of:

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)
    }
}

I get an error along the lines of: "cannot move out of 'pointer.opt' as enum variant 'Some' which is behind a shared reference"
Could someone please explain why this error happens and potential ways around it?

The thing I am working on requires working with a reference to a struct with a similar option in it."

英文:

If I have a struct that is something along the lines of:

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)
    }
}

I get an error along the lines of: "cannot move out of 'pointer.opt' as enum variant 'Some' which is behind a shared reference"
Could someone please explain why this error happens and potential ways around it?

The thing I am working on requires working with a reference to a struct with a similar option in it.

答案1

得分: 3

std::option::Option::as_ref()来处理这种情况:

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

There is std::option::Option::as_ref() for exactly this kind of situation:

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

huangapple
  • 本文由 发表于 2023年2月14日 00:48:23
  • 转载请务必保留本文链接:https://go.coder-hub.com/75438860.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定