gpt4 book ai didi

rust - 如何绑定(bind) Iterator::Item 的类型?

转载 作者:行者123 更新时间:2023-11-29 07:43:04 26 4
gpt4 key购买 nike

我不确定如何为通用迭代器指定迭代器输出类型的界限。在 Rust 1.0 之前,我曾经能够这样做:

fn somefunc<A: Int, I: Iterator<A>>(xs: I) {
xs.next().unwrap().pow(2);
}

但现在,我不确定如何为迭代器的 Item 类型设置界限。

fn somefunc<I: Iterator>(xs: I) {
xs.next().unwrap().pow(2);
}
error: no method named `pow` found for type `<I as std::iter::Iterator>::Item` in the current scope
--> src/main.rs:2:28
|
2 | xs.next().unwrap().pow(2);
| ^^^

我怎样才能让它工作?

最佳答案

您可以引入第二个泛型类型参数并在其上设置界限:

fn somefunc<A: Int, I: Iterator<Item = A>>(mut xs: I) {
xs.next().unwrap().pow(2);
}

您还可以将特征边界放在关联类型本身上

fn somefunc<I: Iterator>(mut xs: I)
where
I::Item: Int,
{
xs.next().unwrap().pow(2);
}

关于rust - 如何绑定(bind) Iterator::Item 的类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27801810/

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