gpt4 book ai didi

types - 在线算法的 Into vs Iterator

转载 作者:行者123 更新时间:2023-11-29 08:23:16 24 4
gpt4 key购买 nike

我正在编写一个在线算法,使用一系列函数实现,这些函数采用迭代器并生成迭代器。

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

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)
}

参见 playground .

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

let input: Vec<u8> = vec![1, 2, 3, 0];
let v: Vec<i16> = decode(input.iter()).collect();

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

fn decode<'a, T>(input: T) -> impl Iterator<Item = i16> + 'a
where
T: Into<Iterator<Item = &'a u8>> + 'a,

playground

我收到一条错误消息,指出返回类型的大小在编译时未知:

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`

这是为什么,有没有更好的办法?

最佳答案

使用 IntoIterator 相反:

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 是一个特征,而特征没有大小。这就是为什么你不能(还)写:

fn example(x: Iterator<Item = ()>) {}
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 定义为:

pub trait Into<T> {
fn into(self) -> T;
}

实现 Into<dyn Iterator> 的东西必须具有函数 fn into(self) -> dyn Iterator , 返回一个特征。由于 trait 没有大小,因此(目前)不能将其返回、存储在变量中或作为参数接受。

另见:

关于types - 在线算法的 Into<Iterator> vs Iterator,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55365706/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com