I get the following error and I'm not sure how to fix it:
error[E0515]: cannot return value referencing temporary value
--> src/core/entity.rs:28:9
|
28 | self.entities.borrow().last().unwrap()
| ----------------------^^^^^^^^^^^^^^^^
| |
| returns a value referencing data owned by the current function
| temporary value created here
I'm trying to create an Entity
struct, store it in a vector inside an EntityManager
and then return a reference to the Entity
. The vector is contained within a RefCell
because I want the EntityManager
to be immutable, hence the interior mutability. I can't return an owned value because I move it when pushing onto the vector.
struct Entity {
id: u32
}
struct EntityManager {
next_id: Cell<u32>,
entities: RefCell<Vec<Entity>>
}
impl EntityManager {
pub fn new() -> EntityManager {
EntityManager {
next_id: Cell::new(0),
entities: RefCell::new(vec![])
}
}
pub fn create_entity(&self) -> &Entity {
let id = self.next_id.get();
let entity = Entity { id };
self.next_id.set(id + 1);
self.entities.borrow_mut().push(entity);
self.entities.borrow().last().unwrap()
}
}
Please could someone help me understand how to solve this?