The source code:
use std::{cell::RefCell, rc::Rc};
struct Group {
children: Vec<Rc<RefCell<Token>>>,
}
enum Extra {
Single,
Group(Group),
}
struct Token {
value: usize,
extra: Extra,
}
struct Status {
last: Option<Rc<RefCell<Token>>>,
}
fn get_prev_token(status: &Status) -> Option<&Rc<RefCell<Token>>> {
// get the last child in status.last
if let Some(last) = &status.last {
let last = last.borrow();
if let Extra::Group(group) = &last.extra {
if let Some(last_child) = group.children.last() {
return Some(last_child);
}
}
}
return None;
}
The background is:
- There is a file-folder-like nested struct
Token
which has an enumextra
to contain the children as aGroup
. - They are all stored as Rc for further multi-ownership x mutable requirements.
- I'm trying to write a fn
get_prev_token()
to get the last child of a group.
Then I met the error:
error[E0515]: cannot return value referencing local variable `last`
--> src/lib.rs:24:16
|
22 | if let Extra::Group(group) = &last.extra {
| ---- `last` is borrowed here
23 | if let Some(last_child) = group.children.last() {
24 | return Some(last_child);
| ^^^^^^^^^^^^^^^^ returns a value referencing data owned by the current function
For more information about this error, try `rustc --explain E0515`.
I understand it's because I use &last.extra
to match the enum which makes it as a local variable. But I have no idea to walk around.
Anyone has an idea to solve this?
Thanks.