Map (Mapping) in 13_Cairo1.0

The article uses the Cairo compiler version 2.0.0-rc0. Since Cairo is being updated rapidly, the syntax may vary slightly in different versions, and the article will be updated to the stable version in the future.

Basic Usage#

Map, also known as a dictionary, is referred to as a dictionary in Cairo. The basic usage includes creating, inserting key-value pairs, and reading data. Let's look at some examples:

use core::debug::PrintTrait;
use dict::Felt252DictTrait;
use traits::Default;

fn main(){
    let mut map : Felt252Dict<felt252> = Default::default();

First, create a dictionary using the Default trait, which returns an initial state dictionary of type Felt252Dict. It is also necessary to specify the variable type in the dictionary. The created map above has the type Felt252Dict<felt252>.

Felt252Dict is the dictionary type supported by Cairo. It can only use variables of type felt252 as keys, and the values can be of various types: u8, u16, u32, u64, u128, felt252. Therefore, it is named Felt252Dict.

To insert key-value pairs, use the insert(key, value) member function, where the first parameter is the key and the second parameter is the value.

Reading is straightforward, just add the key in square brackets map[key].

Ownership of this post data is guaranteed by blockchain and smart contracts to the creator alone.