Traits
Last updated
Last updated
Definition Traits allows unification of types under certain context.
By now you would've worked with various number types like u16
, i32
, f64
etc., All of them behaves similarly to the programmer in general but each of them are represented differently in the computer.
In the above code snippet, eventhough both x and y have the same value semantically, the machine code generated to compute them are different, in fact it take extra clock cycles to compute y
.
The compiler was able to provide the programmer with a uniform semantics but handles all the messy details by itself. This was possible because of Traits in rust, and in this particular example trait is used.
A trait is simply a list of types and function definitions.
In do_something
function the parameter self
refers to the variable of the type that is implementing the trait.
In the last chapter we encountered U256
but currently we have not defined the mechanisms to do additions like U256 + U256
.
What if we want to do U256 + u128
?
How about u128 + u256
?
All this was possible because the Add
trait was defined as follows,
That Rhs
term in the definition allows adding numbers of different types together.
Checkout playground which demonstrates how to implement Foo
trait for various types.
This can be achieved by implementing the trait for U256.
We can see this in action with the following example