lambda - 在结构中存储 lambda 返回迭代器

标签 lambda rust iterator trait-objects

我想在结构中存储将返回迭代器的 lambda。 lambda 是必需的,因为并非所有容器都实现 iter() 函数(例如 String::chars()),所以我需要一种通用方法从容器中获取迭代器。

use std::marker::PhantomData;

struct Foo<F, V, T> {
  foo: F,
  ph: PhantomData<V>,
  ph2: PhantomData<T>,
}

impl<F, V, T> Foo<F, V, T> where
  F: Fn(V) -> dyn Iterator<Item = T> {
}

不幸的是,我收到以下错误:

error[E0277]: the size for values of type `(dyn std::iter::Iterator<Item=T> + 'static)` cannot be known at compilation time
  --> main.rs:9:1
   |
9  | / impl<F, V, T> Foo<F, V, T> where
10 | |   F: Fn(V) -> dyn Iterator<Item = T>
11 | | {
12 | |
13 | | }
   | |_^ doesn't have a size known at compile-time
   |
   = help: the trait `std::marker::Sized` is not implemented for `(dyn std::iter::Iterator<Item=T> + 'static)`
   = note: to learn more, visit <https://doc.rust-lang.org/book/second-edition/ch19-04-advanced-types.html#dynamically-sized-types-and-the-sized-trait>
   = note: required by `std::ops::FnOnce`

我希望我理解它的含义,但我不知道如何修复它。

最佳答案

特征对象,如 dyn Iterator<Item = T> , 在编译时没有已知的大小。这样做的一个后果是函数无法返回“原始”特征对象——编译器需要提前知道调用函数时要在堆栈上保留多少空间。

为了具有已知大小,将特征对象包装在引用或智能指针中。例如,Box :

impl<F, V, T> Foo<F, V, T>
where
    F: Fn(V) -> Box<dyn Iterator<Item = T>>,
{

}

关于lambda - 在结构中存储 lambda 返回迭代器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56723019/

相关文章:

java - 使用 MethodHandles 和 invokedynamic 链接方法调用

amazon-web-services - 如何从 Lambda 获得对 EFS 的写访问权限?

node.js - 我可以使用lambda来压缩一个bucket下的所有图像吗?

rust - 具有对其他结构的不可变引用的结构

java - 使用迭代器时如何确定最后一个元素?

java - java迭代器背后的概念是什么?

python - 使用 tf.map_fn 计算张量的逆

json - Rust & Serde JSON 反序列化示例?

arrays - 在稳定 Rust 中,如何将最小值移出数组,删除其他值?

java - Iterator 接口(interface)中的哪个方法可以移除之前返回的元素?