【发布时间】:2022-01-17 15:47:30
【问题描述】:
我有这个锈代码playground:
use itertools::{repeat_n,RepeatN};
pub trait MyIterator: Iterator {
fn fill1(elem: Self::Item, n1: usize) -> RepeatN<Self::Item>
where
Self::Item: Clone,
{
repeat_n(elem, n1)
}
}
我的问题是我无法调用此方法,因为 rustc 无法推断类型。
// error[E0284]: type annotations needed
// let r: RepeatN<char> = MyIterator::fill1('a', 5);
// ^^^^^^^^^^^^^^^^^ cannot infer type
// note: cannot satisfy `<_ as Iterator>::Item == _`
let r: RepeatN<char> = MyIterator::fill1('a', 5);
我试过了,但它没有编译:
// error[E0229]: associated type bindings are not allowed here
let r: RepeatN<char> = MyIterator::<Item=char>::fill1('a', 5);
如何在此调用中指定Item 的类型?或者特征之外的函数(如itertools::repeat_n)是这里最好的方法?
【问题讨论】:
-
既然不使用
self,那你为什么要把fill1放在一个trait中呢?为什么不直接打电话给repeat_n?对我来说就像x/y problem。 -
嗯,
MyIterator有更多的方法可以采用self或&mut self。我也有fn fill2(elem: Self::Item, n1: usize, n2: usize) -> RepeatN<RepeatN<Self::Item>> { /*...*/ }、fill3等。 -
MyIterator的目的是提供很多实用方法。 -
虽然理论上可以在 trait 中使用不采用
self的方法,但需要在具体类型(例如 playground)上调用它们,因为实现 trait具体类型可以覆盖它们。 → 我的建议是让它们像fn<T: Clone> fill1 (elem: T, n: usize) -> RepeatN<T> { … }这样独立的通用函数 -
谢谢。如果您写该评论作为答案,我很乐意接受。
标签: rust compiler-errors type-inference