Solidity学习之Storage

重点只有一句话:数据有三个存放位置,Storage,Memory,Calldata,只有存储在Storage中的数据会永久存储在区块链中。

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.10;

contract Order{
    uint public _number = 10; //storage

    function getPrice(string calldata brand) public returns (uint){
        uint price = 1; //Memory
        return price;
    }
}

在一个合约中,数据只会出现在三个位置,函数外(Storage),函数参数列表(默认为Memory,也可以为calldata),函数内(Memory),只有存储在Storage中的数据会永久存储在区块链中,其他两个位置的数据会随着函数调用的结束而消失。所以当你想要存储数据在区块链中时,请确保你的修改保存到了Storage字段中。

另外,消耗gas数量从小到大的顺序为 calldata<Memory<Storage,所以在写函数时,请尽量考虑到这个顺序,避免gas消耗过大。