I want to retrieve a reference from a struct wrapped inside an enum. I should not clone or copy the data because i need only to read.
From what i understand the problem comes because i'm trying to return a reference of value contained in a temporary value (a
and b
) that are inside the match arms.
Link to the play ground to replicate the error: code
use std::cell::RefCell;
use std::rc::Rc;
enum Case<T: Custom> {
A(Rc<RefCell<F<T>>>),
B(Rc<RefCell<G<T>>>),
}
impl<T: Custom> Case<T>{
pub fn get_u(&self) -> &T::U {
match self {
Case::A(a) => &a.borrow().u,
Case::B(b) => &b.borrow().u,
}
}
}
trait Custom {
type U;
}
struct F<T: Custom> {
pub u: T::U ,
}
struct G<T: Custom> {
pub u: T::U ,
}
struct H<T: Custom> {
pub h: Case<T>,
}
impl<T: Custom> H<T>{
pub fn foo(&self) {
let u: &T::U = self.h.get_u();
//read u and do stuff with it
}
}
cargo build
error[E0515]: cannot return value referencing temporary value
--> src/lib.rs:11:9
|
11 | / match self {
12 | | Case::A(a) => &a.borrow().u,
13 | | Case::B(b) => &b.borrow().u,
| | ---------- temporary value created here
14 | | }
| |_________^ returns a value referencing data owned by the current function
error[E0515]: cannot return value referencing temporary value
--> src/lib.rs:11:9
|
11 | / match self {
12 | | Case::A(a) => &a.borrow().u,
| | ---------- temporary value created here
13 | | Case::B(b) => &b.borrow().u,
14 | | }
| |_________^ returns a value referencing data owned by the current function