首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在线算法中的Into<Iterator>与Iterator

在线算法中的Into<Iterator>与Iterator
EN

Stack Overflow用户
提问于 2019-03-26 20:28:01
回答 1查看 295关注 0票数 1

我正在写一个在线算法,用一系列函数实现,这些函数需要迭代器和生成迭代器。

当我像这样编写函数时(内容更复杂,但在类型上没有区别):

代码语言:javascript
复制
fn decode<'a, T>(input: T) -> impl Iterator<Item = i16> + 'a
where
    T: Iterator<Item = &'a u8> + 'a,
{
    input.map(|b| i16::from(*b)).filter(|i| *i != 0)
}

游乐场

然而,这使得调用函数不符合人体工程学:

代码语言:javascript
复制
let input: Vec<u8> = vec![1, 2, 3, 0];
let v: Vec<i16> = decode(input.iter()).collect();

我宁愿使用T: Into<Iterator<...,但我不能。当我写签名时:

代码语言:javascript
复制
fn decode<'a, T>(input: T) -> impl Iterator<Item = i16> + 'a
where
    T: Into<Iterator<Item = &'a u8>> + 'a,

游乐场

我收到一个错误,即返回类型的大小在编译时不知道:

代码语言:javascript
复制
error[E0277]: the size for values of type `(dyn std::iter::Iterator<Item=&'a u8> + 'static)` cannot be known at compilation time
 --> src/main.rs:1:1
  |
1 | / fn decode<'a, T>(input: T) -> impl Iterator<Item = i16> + 'a
2 | | where
3 | |     T: Into<Iterator<Item = &'a u8>> + 'a,
4 | | {
5 | |     input.into().map(|b| i16::from(*b)).filter(|i| *i != 0)
6 | | }
  | |_^ doesn't have a size known at compile-time
  |
  = help: the trait `std::marker::Sized` is not implemented for `(dyn std::iter::Iterator<Item=&'a u8> + 'static)`
  = note: to learn more, visit <https://doc.rust-lang.org/book/ch19-04-advanced-types.html#dynamically-sized-types-and-the-sized-trait>
  = note: required by `std::convert::Into`

为什么会这样,还有更好的方法吗?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2019-03-26 20:38:43

使用IntoIterator代替:

代码语言:javascript
复制
fn decode<'a>(input: impl IntoIterator<Item = &'a u8> + 'a) -> impl Iterator<Item = i16> + 'a {
    input.into_iter().map(|b| i16::from(*b)).filter(|i| *i != 0)
}

Iterator是一种性状,性状没有大小。这就是为什么你还不能(还)写:

代码语言:javascript
复制
fn example(x: Iterator<Item = ()>) {}
代码语言:javascript
复制
error[E0277]: the size for values of type `(dyn std::iter::Iterator<Item=()> + 'static)` cannot be known at compilation time
 --> src/lib.rs:1:12
  |
1 | fn example(x: Iterator<Item = ()>) {}
  |            ^ doesn't have a size known at compile-time
  |
  = help: the trait `std::marker::Sized` is not implemented for `(dyn std::iter::Iterator<Item=()> + 'static)`
  = note: to learn more, visit <https://doc.rust-lang.org/book/ch19-04-advanced-types.html#dynamically-sized-types-and-the-sized-trait>
  = note: all local variables must have a statically known size
  = help: unsized locals are gated as an unstable feature

Into被定义为:

代码语言:javascript
复制
pub trait Into<T> {
    fn into(self) -> T;
}

实现Into<dyn Iterator>的东西必须有函数fn into(self) -> dyn Iterator,返回一个特性。由于特征没有大小,所以不能(还)返回、存储在变量中或接受为参数。

另请参阅:

票数 5
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/55365706

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档