如何为任何元素序列实现特征?

问题描述 投票:0回答:1

我试图为任何元素序列实现一个特征,这样它就可以用于向量,数组和切片。到目前为止,我已经尝试了几种方法,但我无法编译它们中的任何一种:(

我有这个特性,以及使用它的函数,以及实现特征的基本数据类型:

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
    }
}

我希望能够为Obj的序列实现这个特性。如果我只是将它限制为向量,它工作正常:

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));
}

但我想让它更通用,以便它适用于数组和切片;我怎样才能做到这一点?

我尝试了以下四次尝试:

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))
    }
}

Playground link

generics rust iterator traits
1个回答
1
投票

1. Iterator-based

这不起作用,因为迭代器需要是可变的才能推进它们,但你的特性需要&self

2. IntoIterator-based

我改变了特征,按值取self然后只实现它以引用Obj。这也允许为任何实现IntoIterator的类型实现它:

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
    }
}

impl<I> Hitable for I
where
    I: IntoIterator,
    I::Item: Hitable,
{
    fn hit(self, val: f64) -> bool {
        self.into_iter().any(|h| h.hit(val))
    }
}

fn main() {
    let o = Obj(2.0);
    let v = vec![Obj(2.0), Obj(3.0)];

    println!("{}", check_hit(&o));
    println!("{}", check_hit(&v));
}

也可以看看:

3. Slice-based

我发现阅读整个错误消息,而不仅仅是一行摘要,可以帮助:

error[E0277]: the size for values of type `[Obj]` cannot be known at compilation time
  --> src/main.rs:28:20
   |
28 |     println!("{}", check_hit(&v[..]));
   |                    ^^^^^^^^^ doesn't have a size known at compile-time
   |
   = help: the trait `std::marker::Sized` is not implemented for `[Obj]`
   = note: to learn more, visit <https://doc.rust-lang.org/book/ch19-04-advanced-types.html#dynamically-sized-types-and-the-sized-trait>
note: required by `check_hit`
  --> src/main.rs:5:1
   |
5  | fn check_hit<T: Hitable>(world: &T) -> bool {
   | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

具体来说,这一点:注意:check_hit要求 - check_hit要求TSized。删除该限制允许此版本工作:

fn check_hit<T: Hitable + ?Sized>(world: &T) -> bool {
//                      ^~~~~~~~
    world.hit(1.0)
}

也可以看看:

© www.soinside.com 2019 - 2024. All rights reserved.