04_Type Conversion in Cairo#
The version of the Cairo compiler used in this article is 2.0.0-rc0. Since Cairo is being rapidly updated, the syntax may vary slightly in different versions, and the article content will be updated to the stable version in the future.
Currently, type conversion in Cairo mainly involves converting various types of integers, such as u8, u16, u256, felt252, etc. Even for u8 and u16, which are very similar types, converting between them is not as easy as in other programming languages.
TryInto & Into traits#
First, let's introduce the two traits provided by these two official libraries. We need to use these two traits to implement the conversion between integer types.
(1). TryInto
The TryInto trait provides the try_into
function, which is used when the value range of the source type is larger than the target type, such as converting felt252 to u32. The return value of the try_into
function is of type Option<T>
🔗Option. If the target type cannot hold the original value, it will return None; if it can, it will return Some. If Some is returned, the return value needs to be converted to the target type using the unwrap
function. Here's an example:
use traits::TryInto;
use option::OptionTrait;
fn main() {
let my_felt252 = 10;
let my_usize: usize = my_felt252.try_into().unwrap();
}
In the above example, a variable my_felt252
of type felt252 is defined, then it is converted to the type Option<T>
using try_into
, and finally the unwrap
function of Option is called to convert the generic variable in Option to a usize variable my_usize
.
(2). Into
With the knowledge of TryInto, Into is easy to understand. The Into trait provides the into
function, which is used when the value range of the target type is larger than the source type, so we don't have to worry about overflow errors and can safely convert. For example, converting u32 to u64. The into
function will directly return the variable of the target type, without the need to use Option for conversion.
use traits::TryInto;
use traits::Into;
use option::OptionTrait;
fn main() {
let my_u8: u8 = 10;
let my_u16: u16 = my_u8.into();
let my_u256: u256 = my_felt252.into();
}
It is worth noting that u256 can also be converted using these two traits.