英文:
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)
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论