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
    }
}
1 Like

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

1 Like