Type Conversion with Into
In Cairo, type conversions are primarily handled through the Into trait. This trait allows you to define how to convert one type into another.
Converting Between Types
The Into trait provides a mechanism for converting between several types. There are numerous implementations of this trait within the core library for conversion of primitive and common types.
For example, we can easily convert a u8 into a u16:
fn main() {
let my_u8: u8 = 5;
let _my_u16: u16 = my_u8.into();
}
We can do something similar for defining a conversion for our own type.
#[derive(Drop, Debug)]
struct Number {
value: u32,
}
impl U32IntoNumber of Into<u32, Number> {
fn into(self: u32) -> Number {
Number { value: self }
}
}
fn main() {
let int: u32 = 30;
let num: Number = int.into();
println!("{:?}", num);
}