I'm running against a wall since days, hopefully somebody of you can help me.
The DatastoreInner is needed because I'm serializing and deserializing the data and it's easier to just do this to the inner struct.
It should be accessible from multiple threads where one calls 'get_item_by_name()' and gets a mutable reference back to the Item to work with.
No matter how I try to solve it, I always get a compiler error.
Even tried lifetime bounds without success.
use std::fmt::Debug;
use std::sync::{Arc, RwLock};
#[derive(Default)]
struct Datastore {
inner: Arc<RwLock<DatastoreInner>>,
}
impl Datastore {
fn get_item_by_name(&self, name: impl AsRef<str>) -> Option<&Box<dyn ItemTrait>> {
self.inner.read().unwrap().items.iter()
.find(|e| e.get_name() == name.as_ref())
}
}
#[derive(Default)]
struct DatastoreInner{
items: Vec<Box<dyn ItemTrait>>,
}
trait ItemTrait: Debug {
fn get_name(&self) -> &str;
}
#[derive(Debug)]
struct Item {name: String}
impl ItemTrait for Item {fn get_name(&self) -> &str {&self.name}}
fn main() {
let ds = Datastore::default();
}
The Error:
error[E0515]: cannot return value referencing temporary value
--> src/main.rs:11:9
|
11 | self.inner.read().unwrap().items.iter()
| ^-------------------------
| |
| _________temporary value created here
| |
12 | | .find(|e| e.get_name() == name.as_ref())
| |________________________________________________^ returns a value referencing data owned by the current function
What am I missing?