说我有一个特征**r
,该特征已为各种几何图元实现。我希望为这些原语列表上的迭代器实现*q + **r = 6+6=12
。
我有验证码(playground):
Intersectable
这会产生错误:
Intersectable
要解决此问题,我尝试用use std::borrow::Borrow;
struct Ray {}
trait Intersectable {
fn intersect(self, ray: &Ray) -> bool;
}
struct Circle {}
impl Intersectable for Circle {
fn intersect(self, _ray: &Ray) -> bool {
true
}
}
impl Intersectable for &Circle {
fn intersect(self, _ray: &Ray) -> bool {
true
}
}
impl<'a, T> Intersectable for T
where T: Iterator<Item = &'a dyn Intersectable> {
fn intersect(self, ray: &Ray) -> bool {
for obj in self {
if obj.intersect(ray) { // Error occurs here
return true;
}
}
return false;
}
}
fn main() {
let objects: [Box<dyn Intersectable>; 2] = [
Box::new(Circle {}),
Box::new(Circle {}),
];
let ray = Ray {};
// I wish to call intersect on the iterator as follows:
println!("Intersection: {}", objects.iter().map(|b| b.borrow()).intersect(&ray));
}
替换对error[E0161]: cannot move a value of type dyn Intersectable: the size of dyn Intersectable cannot be statically determined
--> src/main.rs:24:16
|
24 | if obj.intersect(ray) {
| ^^^
error[E0507]: cannot move out of `*obj` which is behind a shared reference
--> src/main.rs:24:16
|
24 | if obj.intersect(ray) {
| ^^^ move occurs because `*obj` has type `dyn Intersectable`, which does not implement the `Copy` trait
的错误调用,并添加以下实现(playground):
intersect
我在新代码中遇到了相同的错误。当我尝试在引用类型上实现它时,又有一次尝试产生了<T::Item>::intersect(obj, ray)
。
那么可以为
impl Intersectable for &dyn Intersectable {
fn intersect(self, ray: &Ray) -> bool {
(*self).intersect(ray) // Error now occurs here
}
}
实现error[E0119]: conflicting implementations of trait
吗?