[英]Default trait method implementation for all trait objects
I have a trait MyTrait
, and I want all trait objects &MyTrait
to be comparable to each other and to nothing else. 我有一个特征MyTrait
,并且我希望所有特征对象&MyTrait
之间是可比的。 I have that now based on How to test for equality between trait objects? 我现在基于如何测试特征对象之间的相等性来进行分析? . 。
The problem is that I need to use MyTraitComparable
everywhere, instead of MyTrait
. 问题是我需要在MyTraitComparable
地方使用MyTraitComparable
而不是MyTrait
。 Is there a way to get around this? 有办法解决这个问题吗?
use std::any::Any;
trait MyTrait {}
trait MyTraitComparable: MyTrait {
fn as_any(&self) -> &Any;
fn equals(&self, other: &MyTraitComparable) -> bool;
}
impl<S: 'static + MyTrait + PartialEq> MyTraitComparable for S {
fn as_any(&self) -> &Any {
return self as &Any;
}
fn equals(&self, other: &MyTraitComparable) -> bool {
return match other.as_any().downcast_ref::<S>() {
None => false,
Some(a) => self == a,
};
}
}
#[derive(PartialEq)]
struct MyObj {
a: i32,
}
impl MyObj {
fn new(a: i32) -> MyObj {
return MyObj { a };
}
}
impl MyTrait for MyObj {}
fn main() {
assert!(as_trait_obj_and_compare(&MyObj::new(1), &MyObj::new(1)));
}
fn as_trait_obj_and_compare(obj: &MyTraitComparable, another_obj: &MyTraitComparable) -> bool {
obj.equals(another_obj)
}
I tried moving as_any
and equals
to MyTrait
and providing a default implementation, but 我尝试移动as_any
并equals
MyTrait
并提供默认实现,但是
self
in that case, so it doesn't work. 我认为我不能在这种情况下使用self
,所以它不起作用。 trait MyTrait: PartialEq
then I can't create trait objects anymore. 如果我使用trait MyTrait: PartialEq
则无法再创建特征对象。 If you're willing to use a nightly compiler and unstable features, you can use specialization to avoid having two traits: 如果您愿意使用夜间编译器和不稳定的功能,则可以使用专业化来避免两个特征:
#![feature(specialization)]
use std::any::Any;
trait MyTrait {
fn as_any(&self) -> &Any;
fn equals(&self, other: &MyTrait) -> bool;
}
default impl<S: 'static + PartialEq> MyTrait for S {
default fn as_any(&self) -> &Any {
return self as &Any;
}
default fn equals(&self, other: &MyTrait) -> bool {
match other.as_any().downcast_ref::<S>() {
None => false,
Some(a) => self == a,
}
}
}
#[derive(PartialEq)]
struct MyObj {
a: i32,
}
impl MyObj {
fn new(a: i32) -> MyObj {
return MyObj { a };
}
}
impl MyTrait for MyObj {}
fn main() {
assert!(as_trait_obj_and_compare(&MyObj::new(1), &MyObj::new(1)));
}
fn as_trait_obj_and_compare(obj: &MyTrait, another_obj: &MyTrait) -> bool {
obj.equals(another_obj)
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.