Имам много проблеми с животите във връзка с Arcs и RWLocks.
struct ComponentContainer<T>{
id_to_component: HashMap<uint, uint>,
components: Arc<RWLock<~Vec<T>>>
}
id_to_component е карта на идентификационните номера на компоненти към индекс във вътрешните Vec компоненти.
Опитах всичко от интуитивното:
impl<T: Component> ComponentContainer<T>{
fn get<'a>(&'a self, id: uint) -> &'a T {
let idx = self.id_to_component.get(&id);
self.components.read().get(*idx)
}
}
За изключително многословните (ръчно съхраняване на всяка препратка):
impl<T: Component> ComponentContainer<T> {
fn get<'a>(&'a self, id: uint) -> &'a T {
let idx = self.id_to_component.get(&id);
let components: &'a RWLock<~Vec<T>> = &'a *self.components;
let c: &'a RWLock<~Vec<T>> = &'a *components;
let tmp: &'a RWLockReadGuard<'a, ~Vec<T>> = &'a c.read();
let v: &'a ~Vec<T> = &'a **tmp;
v.get(*idx)
}
}
С многословния в крайна сметка получавам грешката:
error: borrowed value does not live long enough
let tmp: &'a RWLockReadGuard<'a, ~Vec<T>> = &'a c.read();
^~~~~~~~~~~~
Според източника за RWLock.read(), върнатата препратка трябва да има посочения живот, освен ако не я чета неправилно.
Редактиране: пълен rustc изход за кратка версия
test.rs:18:9: 18:31 error: borrowed value does not live long enough
test.rs:18 self.components.read().get(*idx)
^~~~~~~~~~~~~~~~~~~~~~
test.rs:16:45: 19:6 note: reference must be valid for the lifetime &'a as defined on the block at 16:44...
test.rs:16 fn get<'a>(&'a self, id: uint) -> &'a T {
test.rs:17 let idx = self.id_to_component.get(&id);
test.rs:18 self.components.read().get(*idx)
test.rs:19 }
test.rs:16:45: 19:6 note: ...but borrowed value is only valid for the block at 16:44
test.rs:16 fn get<'a>(&'a self, id: uint) -> &'a T {
test.rs:17 let idx = self.id_to_component.get(&id);
test.rs:18 self.components.read().get(*idx)
test.rs:19 }
error: aborting due to previous error
~Vec<T>
? От ограничените ми познанияVec<T>
трябва да работи добре. - person   schedule 27.03.2014