Generics
provides a better robust wasy of writing code working with multiple data types without being tied to a specific type. With generics
you can write more clean code without duplication and it provides type-safety as well. The concept of generics can be applied to functions, structs, enumerations etc in Cairo 1.0.
In a function, a generic type is defined by adding placeholder type within angle brackets < >
after the function name. Let us consider the below example:
fn swap<T>(x: T, y: T) -> (T, T) {
(y, x)
}
fn main() {
let (two,one) = swap::<felt>(1, 2);
let (two_128,one_128) = swap::<u128>(1_u128, 2_u128);
}
In the above example, we first define a function named swap
which takes two parameters of type T
and returns the swapped values. Notice T
is wrapped in angle brackets as <T>
in the swap
function, that is how generics is used in a function.
The main ()
function above shows the true power of generics. The first swap in the main ()
function performs a swap of type felt252
and the second swap performs swap with data type uint 128
. Notice how we did not have to define the swap function more than once explicitly defining type felt252
and uint128
. Normally, we would have to define two swap functions one with felt252
data type and the other with u128
data type.
Assignment
Redefine the swap
function above without using generics to perform a swap for both felt252
and u128
data types.