下面是 Solidity 中的函数修饰符详解以及一些简单代码例子:
·public: 声明为公有函数,可以在合约内部和外部调用。
·private: 声明为私有函数,只能在合约内部调用。
·external: 声明为外部函数,只能在合约外部调用。
·internal: 声明为内部函数,只能在合约内部调用。
·pure:修饰符标记该函数为纯函数,表示该函数不会对外部状态产生影响,只能访问内部状态。
pragma solidity ^0.8.7;
contract Example {
uint256 constant public a = 100; //定义常量变量a
uint256 b = 200;
function addA(uint256 x) pure returns (uint256) {//pure修饰符保证函数内不会对外部状态进行修改
return a + x;
}
}
·view:修饰符标记该函数为读取函数,表示该函数不会对外部状态产生影响,只能读取内部状态。
pragma solidity ^0.8.7;
contract Example {
uint256 constant public a = 100; //定义常量变量a
uint256 b = 200;
function readB() view returns (uint256) { //view修饰符保证函数内不会对外部状态进行修改,只能读取
return b;
}
}
·payable:修饰符标记该函数为可支付函数,表示该函数可以接受并处理Ether支付。
pragma solidity ^0.8.7;
contract Example {
uint256 public balance; //定义公共变量balance
function deposit() payable public { // payable修饰符表示该函数可以接受并处理Ether支付
balance += msg.value;
}
}
·constant:修饰符表示该函数为常量函数,它不能修改合约状态,因此它是安全的,也不会消耗任何以太币。
pragma solidity ^0.8.7;
contract Example {
uint256 public balance; // 定义公共变量balance
// 定义常量函数getBalance,返回balance的值
function getBalance() public constant returns (uint256) {
return balance;
}
}
·anonymous:修饰符表示该事件不需要明确的名称,它可以被定义为一个匿名的结构体。
pragma solidity ^0.8.7;
contract Example {
event Transfer(
address indexed _from,
address indexed _to,
uint256 _value
);
// 定义带有anonymous修饰符的事件
event Transfer(address indexed _from, address indexed _to, uint256 _value) anonymous;
function transfer(address _to, uint256 _value) public {
emit Transfer(msg.sender, _to, _value);
}
}
·indexed:修饰符表示该参数为索引参数,在该事件发生后,它可以被检索。
pragma solidity ^0.8.7;
contract Example {
event Transfer(
address indexed _from, // 带有indexed修饰符的_from变量
address indexed _to, // 带有indexed修饰符的_to变量
uint256 _value
);
function transfer(address _to, uint256 _value) public {
emit Transfer(msg.sender, _to, _value);
}
}
附:上一篇我忘了先讲函数了,所以按顺序,要写函数,再讲函数修饰符。