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.
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.
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.
Expanding on Chris' answer, what you probably want is fn equality(&self) -> bool
. fn equality() -> bool
is a static method, also known as an associated function. It is called as Trait::equality()
, not obj.equality()
, and can't access the fields and methods of the object it is called on.