我不确定如何为泛型迭代器的迭代器输出类型指定边界.在Rust 1.0之前,我曾经能够这样做:
fn somefunc<A: Int, I: Iterator<A>>(xs: I) {
xs.next().unwrap().pow(2);
}
Run Code Online (Sandbox Code Playgroud)
但是现在,我不确定如何在迭代器的Item
类型上加上边界.
fn somefunc<I: Iterator>(xs: I) {
xs.next().unwrap().pow(2);
}
Run Code Online (Sandbox Code Playgroud)
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);
| ^^^
Run Code Online (Sandbox Code Playgroud)
我怎样才能让它发挥作用?
Vla*_*eev 17
您可以引入第二个泛型类型参数并将其绑定到:
fn somefunc<A: Int, I: Iterator<Item = A>>(mut xs: I) {
xs.next().unwrap().pow(2);
}
Run Code Online (Sandbox Code Playgroud)
您还可以在关联类型本身上放置特征边界
fn somefunc<I: Iterator>(mut xs: I)
where
I::Item: Int,
{
xs.next().unwrap().pow(2);
}
Run Code Online (Sandbox Code Playgroud)