[英]Implement trait for trait with static function
trait Trait<T> {
fn equality() -> bool;
}
impl<T> PartialEq for Trait<T> {
fn eq(&self, other: &Trait<T>) -> bool {
self.equality()
}
}
Results in 结果是
main.rs:5:23: 5:31 error: the trait `Trait` cannot be made into an object [E0372]
main.rs:5 impl<T> PartialEq for Trait<T> {
Removing the static method makes it compilable. 删除静态方法使其可编译。 Methods with &self parameter compile, too.
具有&self参数的方法也可以编译。
It comes down to a matter known as object safety , which you can find information of in RFC 255 ; 归结为一个称为对象安全的问题 ,您可以在RFC 255中找到的信息。 Huon has a good explanation of object safety in his blog , too.
Huon 在他的博客中也很好地解释了对象安全性 。
Basically, making a trait object requires an implied definition of the trait for its own trait object; 基本上,制作特征对象需要为其自身的特征对象隐含定义特征。 in this case, that would be
impl<'a, T> Trait<T> for Trait<T> + 'a
. 在这种情况下,
impl<'a, T> Trait<T> for Trait<T> + 'a
来说,应为impl<'a, T> Trait<T> for Trait<T> + 'a
。 If it is possible to write meaningful definitions of all the methods, then a trait is object safe. 如果可以编写所有方法的有意义的定义,则特征是对象安全的。 Static methods don't make sense in this context—what would the body of
fn equality() -> bool
be, with no Self
type around to call the equality
method on? 在这种情况下,静态方法没有意义
fn equality() -> bool
的主体将是什么,而周围没有Self
类型可以调用equality
方法? It would need to pull a boolean out of thin air, which it respectfully declines to do. 它需要从布尔中抽出一个布尔值,但是它拒绝这样做。
Expanding on Chris' answer, what you probably want is fn equality(&self) -> bool
. 扩展克里斯的答案,您可能想要的是
fn equality(&self) -> bool
。 fn equality() -> bool
is a static method, also known as an associated function. fn equality() -> bool
是静态方法,也称为关联函数。 It is called as Trait::equality()
, not obj.equality()
, and can't access the fields and methods of the object it is called on. 它称为
Trait::equality()
,而不是obj.equality()
,并且无法访问被调用的对象的字段和方法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.