Issue
I have this rust code 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)
}
}
My Problem is that I can't call this method because rustc can't infer the type.
// 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);
I tried this but it doesn't compile:
// error[E0229]: associated type bindings are not allowed here
let r: RepeatN<char> = MyIterator::<Item=char>::fill1('a', 5);
How can I specify the type of Item
in this call? Or is a function outside of the trait (like itertools::repeat_n
) the best way here?
Solution
Well, you haven't implemented the trait for any types, so no fill1
function actually exists.
If you implement MyIterator
for some type that implements Iterator<Item = char>
, for example std::iter::Empty<char>
, then you'll be able to call fill1
through that type.
use std::iter::Empty;
impl MyIterator for Empty<char> {}
fn main() {
let r: RepeatN<char> = Empty::fill1('a', 5);
}
This is, however, pointless. You will note that Empty
plays no role in the actual function definition - it could have been any iterator. Furthermore there is no sensible generalization of this behavior to other Self
types. This is why itertools::repeat_n
is not a member of the Itertools
trait: it is nonsense as a trait function because it is not a generalization of behavior shared by multiple iterator types.
In Rust, unlike some other languages, not everything has to be a member of a class. If you merely want to put fill1
and related things in a common namespace, simply use a module, which is the most basic unit of code organization.
mod my_iterator {
use itertools::{repeat_n, RepeatN};
fn fill1<T>(elem: T, n1: usize) -> RepeatN<T>
where
T: Clone,
{
repeat_n(elem, n1)
}
}
Answered By - trent Answer Checked By - Clifford M. (PHPFixing Volunteer)
0 Comments:
Post a Comment
Note: Only a member of this blog may post a comment.