How to have a variable size array of variable length strings in contract storage? (StorageVector<StorageString>)

I would like to know if it is possible to have a variable size array that can store variable length strings?
I am aware of StorageString which can be used to store variable length strings.
But how do I use it in combination of a StorageVector or a StorageMap?

It seems I can’t initialize a StorageString outside the storage block?

I would really appreciate any help that you can give me.

1 Like

I’ve just opened an PR that explains how to do this. You can find documentation on this here.

Here is a high level overview:

storage {
    nested_vec_string: StorageVec<StorageString> = StorageVec {},
}

impl Example for Contract {
#[storage(write)]
    fn store_vec() {
        // Setup String to store
        let my_string = String::from_ascii_str("Fuel is blazingly fast");

        // Setup and initialize storage for the StorageString.
        storage.nested_vec_string.push(StorageString {});

        // Method 1: Store the string by accessing StorageString directly.
        storage
            .nested_vec_string
            .get(0)
            .unwrap()
            .write_slice(my_string);

        // Method 2: First get the storage key and then write the string.
        let storage_key: StorageKey<StorageString> = storage.nested_vec_string.get(0).unwrap();
        storage_key.write_slice(my_string);
    }

    #[storage(read, write)]
    fn get_vec() {
        // Method 1: Access the stored string directly.
        let stored_string: String = storage.nested_vec_string.get(0).unwrap().read_slice().unwrap();

        // Method 2: First get the storage key and then access the stored string.
        let storage_key: StorageKey<StorageString> = storage.nested_vec_string.get(0).unwrap();
        let stored_string: String = storage_key.read_slice().unwrap();
    }
}
2 Likes

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