Solidity学习-constant, view, pure三个关键字的区别


  在Solidity中constant、view、pure三个函数修饰词的作用是告诉编译器,函数不改变/不读取状态变量,这样函数执行就可以不消耗gas了,因为不需要矿工来验证。

  在Solidity v4.17之前,只有constant,后来将constant拆成了view和pure。view的作用和constant一样:可以读取状态变量但是不能修改;pure则更为严格,pure修饰的函数不能修改也不能读状态变量,否则不能通过编译。

// SPDX-License-Identifier: GPL-3.0
pragma solidity >=0.7.0 <0.9;

contract ConstantViewPure {
    string name;
    uint public age;

    constructor() {
        name = "johnny";
        age = 29;
    }

    function getAgeByView() public view returns(uint) {
        age += 1; //编译不可以通过,因为view不能修改变量
        return age;
    }

    function getAgeByPure() public pure returns(uint) {
        return age; //编译不可以通过,因为pure禁止读写变量
    }    

    //编译不可以通过,因为去掉了constant关键字
    function getAgeByConstant() public constant returns(uint) {
        age += 1; 
        return age;
    }
}