I am trying to build shared functionality into a trait. I have this
functionality implemented for a Struct.
pub struct AtLeastTwo<T> {
raw: Vec<T>
}
impl <T> AtLeastTwo<T> {
pub fn new(a: T, b: T) -> AtLeastTwo<T> {
AtLeastTwo::new_and(a, b, Vec::new())
}
pub fn new_and(a:T, b: T, mut v:Vec<T>) -> AtLeastTwo<T> {
v.insert(0, a);
v.insert(1, b);
AtLeastTwo {
raw: v
}
}
fn as_slice(&self) -> &[T] {
self.raw.as_slice()
}
fn iter(&self) -> impl Iterator<Item = &T> {
self.as_slice().iter()
}
}
Now I thought to move some of this functionality into a Trait.
trait AtCollection <T> {
fn as_slice(&self) -> &[T];
fn as_vec(self) -> Vec<T>;
fn iter(&self) -> impl Iterator<Item = &T> {
self.as_slice().iter()
}
}
pub struct AtLeastTwo<T> {
raw: Vec<T>
}
impl <T> AtLeastTwo<T> {
pub fn new(a: T, b: T) -> AtLeastTwo<T> {
AtLeastTwo::new_and(a, b, Vec::new())
}
pub fn new_and(a:T, b: T, mut v:Vec<T>) -> AtLeastTwo<T> {
v.insert(0, a);
v.insert(1, b);
AtLeastTwo {
raw: v
}
}
fn as_slice(&self) -> &[T] {
self.raw.as_slice()
}
fn iter(&self) -> impl Iterator<Item = &T> {
self.as_slice().iter()
}
}
impl <T> AtCollection<T> for AtLeastTwo<T> {
fn as_slice(&self) -> &[T] {
self.raw.as_slice()
}
fn as_vec(self) -> Vec<T> {
self.raw
}
}
However, this fails because I cannot use impl Iterator in the Trait
definition. The best I have come up with is too use Box as a
return type. Is this is the only way?