如何解决从 Rust 中的函数返回迭代器返回“大小......在编译时无法知道”
我试过了:
use std::collections::HashMap;
struct Foo {
my_map: HashMap<String,String>,}
impl Foo {
fn bar(&self) -> dyn Iterator<Item = String> {
self.my_map
.values()
.into_iter()
.filter(|m| m.len() == 0)
.collect()
}
}
这会返回
error[E0277]: the size for values of type `(dyn Iterator<Item = String> + 'static)` cannot be kNown at compilation time
use std::collections::HashMap;
struct Foo {
my_map: HashMap<String,}
impl Foo {
fn bar(&self) -> Box<dyn Iterator<Item = String>> {
Box::new(
self.my_map
.values()
.into_iter()
.filter(|m| m.len() == 0)
.collect(),)
}
}
由于无法推断 Box
的类型而失败。
在尝试添加显式类型 arg 后:
use std::collections::HashMap;
struct Foo {
my_map: HashMap<String,}
impl Foo {
fn bar(&self) -> Box<dyn Iterator<Item = String>> {
Box::<dyn Iterator<Item = String>>::new(
self.my_map
.values()
.into_iter()
.filter(|m| m.len() == 0)
.collect(),)
}
}
它现在失败了:
error[E0599]: no function or associated item named `new` found for struct `Box<dyn Iterator<Item = String>>` in the current scope
--> src/lib.rs:10:45
|
10 | Box::<dyn Iterator<Item = String>>::new(
| ^^^ function or associated item not found in `Box<dyn Iterator<Item = String>>`
|
= note: the method `new` exists but the following trait bounds were not satisfied:
`dyn Iterator<Item = String>: Sized`
我对这门语言很陌生,所以不确定这里发生了什么。在这种情况下如何返回迭代器?
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。