Why is the keyword 'memory' needed in defining a struct variable in a function?

Hi guys, as the title suggests, a struct variable defined in a function requires the memory keyword, and the other three possibilities given in the code snippet below are all returning errors. I’m just wondering why bother to ask for memory at all if this is the only possible way of instantiating a struct variable in a function. Can it be made just like a state variable on the top level defaults as internal? Thanks.

// SPDX-License-Identifier: MIT

pragma solidity 0.8.17;

contract Test {

    struct Vars {
        uint256 value;
        bool flag;
    }

    function myFun1() external {
        Vars memory vars = Vars({
            value: 1,
            flag: true
        });
        // Do Sth;
    }

    function myFun2() external {
        Vars storage vars = Vars({
            value: 1,
            flag: true
        });
        // Do Sth;
    }

    function myFun3() external {
        Vars calldata vars = Vars({
            value: 1,
            flag: true
        });
        // Do Sth;
    }

    function myFun4() external {
        Vars vars = Vars({
            value: 1,
            flag: true
        });
        // Do Sth;
    }
}

Answer by example:

contract Test {

    struct Vars {
        uint256 value;
        bool flag;
    }

    mapping(uint256 => Vars) private varsTable;

    function myFunc(uint256 id, uint256 value, bool flag) external {
        Vars storage vars = varsTable[id];
        vars.value = value; // update varsTable[id].value
        vars.flag = flag; // update varsTable[id].flag
    }
}
2 Likes

Yes, that makes sense. How could I forget this. Thanks.

1 Like

When defining a struct variable within a function in Solidity, you must use the keyword memory to specify that the variable should be created in the function’s memory. The other options (storage and calldata) are not suitable for this purpose. If you want default values for a struct like a state variable, define it outside the function at the contract level.

@Worthy:

That’s wrong. Check out the example given in the previous answer (above).

4 Likes