A map is just a bunch of key:value pairs.
The maps functionality can be imported onto your smart contract using this
use std::simple_map::{Self, SimpleMap};
The Self
attribute imports all the functions necessary for us to import with the simple map.
Creating a SimpleMap
To create the above mapping in a SimpleMap, you can write the following code:
fun create_map(): SimpleMap<u64, String> {
let my_map: SimpleMap<u64, String> = simple_map::create();
simple_map::add(&mut my_map, 1, utf8(b"UAE"));
simple_map::add(&mut my_map, 2, utf8(b"RUS"));
simple_map::add(&mut my_map, 3, utf8(b"MEX"));
simple_map::add(&mut my_map, 4, utf8(b"COL"));
return my_map
}
This function, when called, returns a simple map object with the key being a u64 and the value being a string.
my_map
is the object made inside the local scope which will be our mapping. We initialize the mapping with the simple_map::create()
function.
We can then add key:value pairs to this mapping using the simple_map::add()
function. Its parameters are a mutable pointer to the mapping object, the key, and the value. Make sure you adhere to the structure that you have defined when you add your data into the mapping, or it will throw an error.
Checking the length of the map object
To check the length of the SimpleMap object we just made, we use this function:
fun check_map_length(my_map: SimpleMap<u64, String>): u64 {
let value = simple_map::length(&mut my_map);
return value
}
This function takes in a map of this structure as a parameter, checks and returns its length using the simple_map::length()
function. The parameter for that function is a mutable pointer to the map object.
Removing pairs from the map
fun remove_from_map(my_map: SimpleMap<u64, String>, key: u64): SimpleMap<u64, String> {
simple_map::remove(&mut my_map, &key);
return my_map
}
This function takes in 2 parameters, one being the map itself, 2 being the key which needs to be removed. This returns a map of the same structure, as shown.
The pair can be removed using the simple_map::remove()
function who’s input parameters are 2 things. The first is a mutable reference to the map object, and the second one is the reference of the key to be removed.
Testing this
#[test_only]
use std::debug::print;
#[test]
fun test_function(){
let my_map = create_map();
let country = simple_map::borrow(&mut my_map, &2);
print(country); // Prints RUS
let length = check_map_length(my_map);
print(&length); // Prints 4
let new_map = remove_from_map(my_map, 2);
print(&check_map_length(new_map)); // Prints 3
}