Traits
Last updated
Last updated
A trait is similar to an interface in other programming languages.
It defines a set of methods that a type must implement, allowing you to specify what functionality a type provides without dictating how it provides it.
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.
Traits can provide default method implementations that types can override.
The impl Trait
syntax works for straightforward cases but is actually syntax sugar for a longer form known as a trait bound.
We can also specify more than one trait bound using +
syntax.
References:
This exercise is easy we just need to implement trait item/function append_bar
inside the impl AppendBar for String
block.
This exercise also similar like the first one.
We need to create implementation of AppendBar
trait for Vec<String>
Because we want to mutate the vector (self
) we need to add mut
syntax.
The full implementation will look like this:
In this exercise we need to create default implementation of licensing_info
that will return "Default license"
.
This default implementation will be called if not the trait is not implemented for the specified type.
In this exercise we need to change the function signature of compare_license_types
to accept both SomeSoftware
and OtherSoftware
type.
We can do this using generics.
Or we can also use impl Trait
syntax like this:
In this exercise we need to update function signature of some_func
to accept implementation of SomeTrait
and OtherTrait
.
It means that given type must implement both trait.
We can do this by using +
syntax like this:
You can read more about it in here: