Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do I not have to implement the Any trait for a type even though it is a required?

Tags:

rust

When defining a trait, my understanding is that trait names on the right side of the : are required any time the left side is implemented. If so, why does the following compile:

use std::any::Any;

trait Trait: Any {}

struct Thing {}

impl Trait for Thing {}

The following does not compile (which matches my understanding of what is correct)

trait RequiredTrait {}
trait Trait: RequiredTrait {}

struct Thing {}

impl Trait for Thing {}
like image 478
Aakil Fernandes Avatar asked Nov 14 '18 22:11

Aakil Fernandes


People also ask

How do you implement traits?

Implementing a trait on a type is similar to implementing regular methods. The difference is that after impl , we put the trait name we want to implement, then use the for keyword, and then specify the name of the type we want to implement the trait for.

What is the point of traits in Rust?

A trait tells the Rust compiler about functionality a particular type has and can share with other types. Traits are an abstract definition of shared behavior amongst different types. So, we can say that traits are to Rust what interfaces are to Java or abstract classes are to C++.

Can traits have fields Rust?

Traits can't have fields. If you want to provide access to a field from a trait, you need to define a method in that trait (like, say, get_blah ).

What is blanket implementation in Rust?

What are blanket implementations? Blanket implementations leverage Rust's ability to use generic parameters. They can be used to define shared behavior using traits. This is a great way to remove redundancy in code by reducing the need to repeat the code for different types with similar functionality.


1 Answers

std::any contains the implementation:

impl<T> Any for T
where
    T: 'static + ?Sized, 

That means that any type implements Any as long as any references it contains are 'static and the type is sized. Your Thing struct meets both of those requirements so it does implement Any and your code compiles.

like image 176
sepp2k Avatar answered Oct 16 '22 09:10

sepp2k