【发布时间】:2019-10-31 08:24:22
【问题描述】:
我需要在'static 结构中存储一个fn(I) -> O(其中I 和O 可以是引用)。 O 需要是具有'static 泛型关联类型的特征,该关联类型也存储在结构中。 I 和 O 本身都不会存储在结构中,因此它们的生命周期无关紧要。但是编译器仍然在抱怨I 活得不够长。
trait IntoState {
type State: 'static;
fn into_state(self) -> Self::State;
}
impl IntoState for &str {
type State = String;
fn into_state(self) -> Self::State {
self.to_string()
}
}
struct Container<F, S> {
func: F,
state: S,
}
impl<I, O> Container<fn(I) -> O, O::State>
where
O: IntoState,
{
fn new(input: I, func: fn(I) -> O) -> Self {
// I & O lives only in the next line of code. O gets converted into
// a `'static` (`String`), that is stored in `Container`.
let state = func(input).into_state();
Container { func, state }
}
}
fn map(i: &str) -> impl '_ + IntoState {
i
}
fn main() {
let _ = {
// create a temporary value
let s = "foo".to_string();
// the temporary actually only needs to live in `new`. It is
// never stored in `Container`.
Container::new(s.as_str(), map)
// ERR: ^ borrowed value does not live long enough
};
// ERR: `s` dropped here while still borrowed
}
【问题讨论】:
-
问题似乎在于关联的泛型类型,如果我删除它(插入
String作为返回类型)它开始工作。 playground。但对于我的应用程序逻辑来说,它是通用的。 -
我是否应该更新标题和描述以更好地反映问题(这里的问题不是存储 fn,而是
IntoStatetrait/"missing" 泛型类型)? -
我会以一种与静态生命周期无关的方式更新它,但它仍然反映编译器的错误消息(因为人们会搜索那些误导性的东西)
标签: rust