Reading & Doing
Old Tiny Games
学习折腾了大概一周,总算有了一点成果: code
生命周期就像是"显式"的说明一个引用的生命周期。
目前了解到rust生命周期可分为三类:
声明一个trait
pub struct PersistedOrigin;
pub trait Persist: Clone + 'static {
fn ptr(&self) -> PersistedOrigin {
PersistedOrigin
}
}
某一类型实现该trait
impl<T: 'static> Persist for State<T> {
fn ptr(&self) -> PersistedOrigin {
PersistedOrigin
}
}
如果仅使用 RefCell 会报多线程错误
pub struct RefContainer<T>(pub Rc<RefCell<T>>);
如果需要取出 T 的值,在外部包裹一层 Option,通过take方法取得。
pub struct State<T> {
container: RefContainer<Option<T>>,
}
impl<T> State<T> {
pub fn value(&self) -> Ref<'_, T> {
Ref::map(self.container.current(), |v| {
v.as_ref().expect("Cannot get state!!!!!")
})
}
pub fn set(&mut self, f: impl FnOnce(T) -> T) {
let val = self.container.current_mut().take();
let new_v = val.map(f);
self.container.set_current(new_v);
}
}