为什么这段代码会编译?
fn get_iter() -> impl Iterator<Item = i32> {
[1, 2, 3].iter().map(|&i| i)
}
fn main() {
let _it = get_iter();
}
Run Code Online (Sandbox Code Playgroud)
[1, 2, 3]是一个局部变量并iter()借用它.此代码不应编译,因为返回的值包含对局部变量的引用.
我需要在结构中存储fn(I) -> O(其中I&O可以是引用)'static。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 …Run Code Online (Sandbox Code Playgroud)