Solidity Question | Gas error

1.- does this function with “for” can provoke an out of gas error ?

2.- what is the best way to retrieve this data without for?

Thanks in advance

Hi,

It doesn’t seem like it’s updating state in the blockchain so it must be free of gas.

If your second question is not exactly for a “same output in a different way”, then no, mappings are index-free data types, we can’t get a list of mapping as long as we didn’t save them into an another array. But if you want for a ‘name’ value you can directly ask of it’s field inside of a mapping.

It also seems the ‘names’ depend on existence of token ids in your code. So I would go for a struct-type array to keep the names and token ids

contract BetterStorageDesign {

    struct Instances {
        uint id;
        string name;
        // as mush as needed fields...
    }

    Instances[] public instanceList;

    function create(string memory newName) public {
        Instances memory newInstance;
        newInstance.name = newName;
        newInstance.id = instanceList.length; // or in an ERC721 contract, = tokenId
        instanceList.push(newInstance);
    }

    function read() public view returns(Instances[] memory) {
        return instanceList; // returns tuple 💫
    }

}

I strongly recommend studying on Storage Design lecture in solidity course once more. You probably noticed that around four different storage designs there, would eventually be needed in almost every contract that have CRUD basics.

I wish enjoyable studying times and
Success!

2 Likes