Struct Map
pub struct Map<K, V, Context> {
pub context: Context,
/* private fields */
}
Fields
context: ContextImplementations
impl<Context, K, V> Map<K, V, Context>
pub fn at<let N: u32>(self, key: K) -> V
where
K: ToField,
V: StateVariable<N, Context>
Returns the state variable for a key.
This derives a unique storage slot for key and returns a state variable of type V at that slot. It is
equivalent to accessing a mapping via the [] operator in Solidity (e.g. balances[user] would be
balances.at(user)).
Example
#[external("utility")]
fn get_election_vote_tallies(election: ElectionId) -> u128 {
self.storage.vote_tallies.at(election).read()
}
A key-value container for state variables.
A
Mapwraps another state variable type (the 'value') and creates independent instances of it for each key, resulting in effectively as many state variables as there are key values. This behavior is similar to a Soliditymapping (K => V).Use Cases
Any scenario in which a fixed number of variables is insufficient to represent contract state requires
Mape.g. per-election configuration in a voting contract, per-user state, etc.Mapalso composes naturally into more complex containers: an array could be implemented as aMapwith indices as keys.Note that some private state variables, such as
PrivateMutableandPrivateSetcannot be wrapped in aMap. These types implement theOwnedStateVariabletrait, and as such should instead be wrapped using theOwnedcontainer, which can be thought of as a specialization ofMapfor private state 'owned' by a single account.Examples
Since
Mapis also aStateVariable, it is declared in the contract's#[storage]struct along with all others:Multiple
MapsThere is no limit to how many
Mapcontainers a contract can have, andMaps can themselves wrap otherMaps, resulting in nested layouts.Requirements
The value type
Vmust implement theStateVariabletrait. The key typeKmust implement theToFieldtrait in such a way that theFieldrepresentation is unique for each key.For key types that cannot be converted into a
Field, consider wrapping them in a type that implementsToFieldas the hash of the key.Implementation Details
Like all other state variables,
Mapgets assigned a unique storage slot. It uses this value to derive unique storage slots for each key, resulting in independent state variables. Nothing gets stored atMap's storage slot. This is equivalent to Solidity's implementation ofmapping.Because the storage slot derivation is done using a hash function, it is not possible to compute the key (preimage) used to obtain a given derived state variable slot.