使用静态函数为 trait 实现 trait [英] 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()
}
}
结果
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> {
删除静态方法使其可编译.带有 &self 参数的方法也可以编译.
Removing the static method makes it compilable. Methods with &self parameter compile, too.
推荐答案
归结为一个称为对象安全的问题,您可以在 RFC 255;Huon 也在他的博客中很好地解释了对象安全.
It comes down to a matter known as object safety, which you can find information of in RFC 255; Huon has a good explanation of object safety in his blog, too.
基本上,创建一个 trait 对象需要为它自己的 trait 对象隐式定义 trait;在这种情况下,这将是 impl<'a, T>性状 <T>对于 Trait <T>+ 'a
.如果可以为所有方法编写有意义的定义,那么特征就是对象安全的.静态方法在这种情况下没有意义——fnquality() ->bool
是,没有 Self
类型来调用 equality
方法?它需要凭空提取一个布尔值,但它恭敬地拒绝这样做.
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
. 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? It would need to pull a boolean out of thin air, which it respectfully declines to do.
这篇关于使用静态函数为 trait 实现 trait的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!