У меня много проблем с временем жизни в отношении 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