Cannot get the following code to compile after multiple attempted variations. All I am trying to do is get a Generic trait to work for a Slice which, in turn, is itself generic.
Playground for the code below here.
#![feature(associated_type_defaults)]
use std::ops::{Mul, AddAssign};
trait Foo<'a, T: 'a> {
type Item = &'a [T];
fn assert_equal(&self, other: Self::Item) {
assert_eq!(self.len(), other.len());
}
}
impl<'a, T> Foo<'a, T> for &'a [T]
where T: Mul<T, Output=T> + AddAssign {}
pub fn main() {
let foo = &[1, 2, 3][..];
println!("{:?}", foo.assert_equal(&[3, 4, 5]));
}
Getting error about len()
not available on &Self
:
9 | assert_eq!(self.len(), other.len());
| ^^^ method not found in `&Self`
= help: items from traits can only be used if the type parameter is bounded by the trait
help: the following trait defines an item `len`, perhaps you need to restrict type parameter `Self` with it:
And, going by compiler suggestion, If I make the trait to be bounded (which I am not sure is the correct way) with the following change:
trait Foo<'a, T: 'a> where Self: Iterator {
// Rest of code being same
}
I get another error:
13 | impl<'a, T> Foo<'a, T> for &'a [T]
| ^^^^^^^^^^ `T` is not an iterator
And now if I change where
on impl
to include + Iterator
, I am back to the original error.
Any help or guidance appreciated!