In Cairo, traits
and implementations
are used to define and implement functionality that can be used across different types
.
Traits are very similar to interfaces in traditional Object Oriented(OO) languages, but with some key differences.
You could think of a trait as a means to define an interface for a specific type.
We define a trait using the trait
keyword followed by the name of the trait
. In the trait block, we specify the signature of the functions that we want that specific trait to implement.
Traits define a set of methods that must be implemented by any component that uses the trait. Here is an example of a simple trait definition in Cairo:
trait Maths {
fn add(x: u8, y: u8) -> u8;
}
This trait
, called Maths
, defines a single method called add
. In other words we are saying that every type
that uses this trait needs to implement the add
function.
traits
can contain multiple function signatures, for example, we can update the trait
(Maths) above to:
trait Maths {
fn add(x: u8, y: u8) -> u8;
fn subtract(x: u8, y: u8) -> u8;
fn multiply(x: u8, y: u8) -> u8;
}
Implementations are used to define the behavior of a type
that uses a trait
. The impl
keyword is used to define implementations on traits.
Here is a simple implementation of the Maths trait
above:
impl MathImpl of Maths {
fn add(x: u8, y: u8) -> u8 {
x + y
}
fn subtract(x: u8, y: u8) -> u8 {
x - y
}
fn multiply(x: u8, y: u8) -> u8 {
x * y
}
}
You could then call the defined traits from functions like this:
fn main(x: u8, y: u8) -> u8 {
Maths::add(x, y)
}