solidity 引用型別修飾符memory、calldata與storage 常量修飾符Constant與Immutable區別

行者akai發表於2023-03-07

在solidity語言中

引用型別修飾符(引用型別為儲存空間不固定的數值型別)

memory、calldata與storage,它們只能修飾引用型別變數,比如字串、陣列、位元組等...

memory 適用於方法傳參、返參或在方法體內使用,使用完就會清除掉,釋放記憶體

calldata 僅適用於方法傳參,修飾該變數的值不能修改

storage 僅適用於方法體內,而且它的指標必須指向鏈上資料。使用完,鏈上資料將儲存最新狀態

 

常量修飾符

constant 編譯前已經確定,編譯後不能再修改常量的值

constant 它不是狀態變數,所以它不儲存在插槽(Slot)裡面,獲取該常量的方法修飾必須是Pure,而不是View

immutable 它是狀態變數,所以它儲存在插槽(Slot)裡,獲取該變數的方法修飾必須是View,而不是Pure

immutable 必須在建構函式裡面賦值,之後就不能再修改

 

contract ConstantImmutable{
 
    string private constant name ="Thinkingchain";
    uint private immutable age;
 
    constructor(uint256 _age){
        age = _age;
        //age = 10;
    }

    function getName() public pure returns(string memory){
        return name;
    }

    function getAge() public view returns(uint){
        return age;
    }
    /*
    function setAge() public{
        age++;
    }
    */
}

相關文章