Git repo: https://github.com/caveofprogramming/rust/
Traits allow us, among other things, to specify what methods a struct must have.
The following trait is called “Stats” and specifies that any struct that implements it must have four methods with the specified signatures.
The sum_square method also has a default implementation, which will be used if we don’t specify a new implementation for any struct that implements this trait.
Here’s a struct which at the moment does not implement the Stats trait:
To make the Point struct implement the Stats trait, at the minimum we have to supply implementations for all the methods that don’t have default implementations in the trait.
We can now use these methods:
Note that, in order to create the default implementation of sum_squares() here, I had to have some way of specifying that structs that implement the trait must have methods x() and y() that return the values to be squared and summed.
We can’t otherwise access fields of the struct in the trait implementation, since the trait doesn’t know anything about what kind of structs it might in the future implement it and doesn’t know about, or have access to, the x and y fields.