I have the following code:
pub struct Tree<T> {
root: Box<Node<T>>,
elements: HashSet<T>,
}
impl<T> Tree<T> {
pub fn new<I>(source: I) -> Option<Tree<T>>
where
I: std::iter::Iterator,
<I as Iterator>::Item: Hash,
<I as Iterator>::Item: Eq,
{
...
}
How do I propagate <I as Iterator>::Item
type to T
? In other words, how can I write code like this:
let tree = Tree::new("test".chars());
CodePudding user response:
You can set the Iterator type with Iterator<Item = T>
. So your code would look like this
impl<T> Tree<T> {
pub fn new<I>(source: I) -> Option<Tree<T>>
where
I: Iterator<Item = T>,
T: Hash,
T: Eq,
{
...
}
}
If you want your whole Tree to just be able to maintain types that implement the Hash
and Eq
trait. You should define that in the implementation.
impl<T> Tree<T>
where
T: Hash,
T: Eq,
{
pub fn new<I>(source: I) -> Option<Tree<T>>
where
I: Iterator<Item = T>,
{
None
}
}
That way you won't have to define it for every method.
[Edit]
Removed trait bounds from struct because of this