Maps are a type of collection available on Coco. Maps contain are made up of key-value pairs. Each key in the map must be unique and can be mapped to a single value only.
make(Map[U64]String)
The make
command can be used to initialize an empty map.
memory mp2 = Map[U64]String{3: "No", 4: "Yes"}
Here the mp2 variable is initialized with a set of key-value pairs using the syntax shown.
The len
operator can be used to get total number of keys present in a map.
joined = merge(mp, mp2)
Maps can be merged using the merge operator. If the keys overlap, the second map pairs overwrite the first. With this operation joined will contain union of all keys present in ‘mp’ and ‘mp2’.
To remove a key/value from the map, one can use remove
function. It doesn’t return the removed value, if we try to remove a non-existent key, remove
doesn’t do anything.
Membership check with ?
operator
To check if a map has an element at some key, one can use the “has” operator ?
that returns a boolean “true” if the element exists.
memory exists = m["hi"]?
coco Maps
endpoint invokable Test1()->(output1 Map[String]U64, output2 Map[String]U64, length U256, joined Map[U64]String):
memory mp = make(Map[U64]String)
mp[1] = "Hello"
mp[2] = "Hi"
memory mp2 = Map[U64]String{3: "No", 4: "Yes", 5:"Wrong"}
remove(mp2, 5) // removes the key/value 5:Wrong
length = len(mp)
joined = merge(mp, mp2)
return (output1: mp, output2: mp2, length:length, joined:joined)