Workaround for creating a StorageMap as part of a struct or an enum

Currently, Sway does not support StorageMap as a component of a complex type such as a struct or an enum. For instance, the following definition is not allowed in Sway:

Struct Wrapper {
    map1: StorageMap<b256, bool>,
    map2: StorageMap<bool, u64>,

What could be a possible workaround for this?


A StorageMap only exists in storage (i.e., it is discarded at the end of the script/contract). At the moment, there is no support for a Struct inside storage that contains the StorageMap.
Same is applicable to enums.

A possible workaround for using storage maps as components of complex types is to use the storage map in storage as usual, but alter the key to be a tuple containing your original key and pass along a unique identifier for the struct. For instance:

storage {
    map1: StorageMap<(b256, struct_id), bool> = StorageMap {},
    map2: StorageMap<(bool, struct_id), u64> = StorageMap {},

The StorageMap has the following structure StorageMap<key, value> where the key is what is used to index into the hash table in order to retrieve the value at that location in memory.
It doesn’t matter what the key is, so it can either be a struct, a tuple of values, or an enum variant.

The above definition allows you to index into the storage map using storage.var.get((key, struct id)).

1 Like

This topic was automatically closed 20 days after the last reply. New replies are no longer allowed.