返回的盒装值的生命周期不够长

时间:2018-09-11 09:29:40

标签: rust

我正在学习Rust,并认为我会尝试制作一个非常简单的反应式流库。代码示例如下:

trait Observable<T> {
    // some stuff for emitting values when requested
}

trait Mappable<T, U> {
    fn map(self, f: fn(&T) -> U) -> Box<dyn Observable<U>>;
}

struct Just<T> {
    value: T
}

impl<T> Observable<T> for Just<T> {}

impl<T, U: 'static> Mappable<T, U> for Just<T> {
    fn map(self, f: fn(&T) -> U) -> Box<dyn Observable<U>> {
        Box::new(Just { value: f(&self.value) })
    }
}

为了使其工作,我需要在'static的{​​{1}}实现中为U类型赋予Mappable生存期。没有它,编译器会抱怨:

Just

我不明白为什么编译器会抱怨这一点,因为该值放在error[E0310]: the parameter type `U` may not live long enough --> src/lib.rs:17:9 | 15 | impl<T, U> Mappable<T, U> for Just<T> { | - help: consider adding an explicit lifetime bound `U: 'static`... 16 | fn map(self, f: fn(&T) -> U) -> Box<dyn Observable<U>> { 17 | / Box::new(Just { 18 | | value: f(&self.value), 19 | | }) | |__________^ | note: ...so that the type `Just<U>` will meet its required lifetime bounds --> src/lib.rs:17:9 | 17 | / Box::new(Just { 18 | | value: f(&self.value), 19 | | }) | |__________^ 内。

提供Box的生命周期显然是可行的,但我担心它会造成内存泄漏,因为流中的中间阶段要等到程序退出后才能释放。

我认为解决方案是使'static的生存期与U相同。但是我所做的所有尝试都失败了。

如何在不使用T的情况下表达以上代码?

0 个答案:

没有答案
相关问题