I am trying to implement a trait for any sequence of elements, so that it will work for vectors, arrays and slices. So far I've tried several approaches, but I can't compile any of them :(
I have this trait, and a function that uses it, and a basic data type implementing the trait:
trait Hitable {
fn hit(&self, val: f64) -> bool;
}
fn check_hit<T: Hitable>(world: &T) -> bool {
world.hit(1.0)
}
struct Obj(f64);
impl Hitable for Obj {
fn hit(&self, val: f64) -> bool {
self.0 > val
}
}
I'd like to be able to implement that trait for sequence of Obj
's.
It works fine if I just restrict it to vectors:
impl<T> Hitable for Vec<T>
where
T: Hitable,
{
fn hit(&self, val: f64) -> bool {
self.iter().any(|h| h.hit(val))
}
}
fn main() {
let v = vec![Obj(2.0), Obj(3.0)];
println!("{}", check_hit(&v));
}
But I want to make it more generic so that it works for arrays and slices; how can I do that?
I tried the following four attempts:
Attempt #1: for iterator on Hitables.
// It's not clear how to call it:
// vec.iter().hit(...) does not compile
// vec.into_iter().hit(...) does not compile
//
impl<T, U> Hitable for T
where
T: Iterator<Item = U>,
U: Hitable,
{
fn hit(&self, val: f64) -> bool {
self.any(|h| h.hit(val))
}
}
Attempt #2: for something which can be turned into iterator.
// Does not compile as well:
//
// self.into_iter().any(|h| h.hit(val))
// ^^^^ cannot move out of borrowed content
//
impl<T, U> Hitable for T
where
T: IntoIterator<Item = U>,
U: Hitable,
{
fn hit(&self, val: f64) -> bool {
self.into_iter().any(|h| h.hit(val))
}
}
Attempt #3: for slices.
// This usage doesn't compile:
// let v = vec![Obj(2.0), Obj(3.0)];
// println!("{}", check_hit(&v));
//
// It says that Hitable is not implemented for vectors.
// When I convert vector to slice, i.e. &v[..], complains about
// unknown size in compilation time.
impl<T> Hitable for [T]
where
T: Hitable,
{
fn hit(&self, val: f64) -> bool {
self.iter().any(|h| h.hit(val))
}
}
Attempt #4: for Iterator + Clone
// let v = vec![Obj(2.0), Obj(3.0)];
// println!("{}", check_hit(&v.iter()));
//
// does not compile:
// println!("{}", check_hit(&v.iter()));
// ^^^^^^^^^ `&Obj` is not an iterator
//
impl<T, U> Hitable for T
where
T: Iterator<Item = U> + Clone,
U: Hitable,
{
fn hit(&self, val: f64) -> bool {
self.clone().any(|h| h.hit(val))
}
}