0

From solidity docs (https://docs.soliditylang.org/en/v0.8.4/types.html#data-location ) -

Every reference type has an additional annotation, the “data location”, about where it is stored. There are three data locations: memory, storage and calldata. Calldata is a non-modifiable, non-persistent area where function arguments are stored, and behaves mostly like memory.

Further down in the docs it says this:

Assignments from storage to a local storage variable also only assign a reference.

What is local storage ? How is it different from storage

Before you close this down as duplicate , I have read the other answers and none of them answer this comprehensively .

1 Answer 1

1

Local storage references to storage variables inside a function, which also allows data manipulation.

Better understand with this code example:


contract Example {
    // State variables (storage)
    uint256[] public myArray;
    mapping(address => uint256) public myMapping;

    struct MyStruct {
        uint256 x;
        uint256 y;
    }
    MyStruct public myStruct;
    function setValues() public {

        // Local storage references for reference types
        uint256[] storage localArray = myArray;
        mapping(address => uint256) storage localMapping = myMapping;
        MyStruct storage localStruct = myStruct;

        // Modify values through local storage references
        localArray.push(1);
        localMapping[msg.sender] = 100;
        localStruct.x = 10;
        localStruct.y = 20;
    }
}

You can see we are not directly updating the storage variable, instead, we are updating the local reference and it also updates the original storage variable.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.