枚举
枚举是在 Solidity 中创建用户定义类型的一种方式。它们可以显式转换为所有整数类型,但不允许隐式转换。整数的显式转换在运行时检查该值是否在枚举范围内, 否则会导致Panic 错误。枚举至少需要一个成员,声明时它的默认值是第一个成员。枚举不能有超过 256 个成员。
数据表示与 C 中的枚举相同:选项由从 开始的后续无符号整数值表示0。
使用type(NameOfEnum).minandtype(NameOfEnum).max你可以获得给定枚举的最小值和最大值。
// SPDX-License-Identifier: GPL-3.0
pragma solidity ^0.8.8;
contract test {
enum ActionChoices { GoLeft, GoRight, GoStraight, SitStill }
ActionChoices choice;
ActionChoices constant defaultChoice = ActionChoices.GoStraight;
function setGoStraight() public {
choice = ActionChoices.GoStraight;
}
// Since enum types are not part of the ABI, the signature of "getChoice"
// will automatically be changed to "getChoice() returns (uint8)"
// for all matters external to Solidity.
function getChoice() public view returns (ActionChoices) {
return choice;
}
function getDefaultChoice() public pure returns (uint) {
return uint(defaultChoice);
}
function getLargestValue() public pure returns (ActionChoices) {
return type(ActionChoices).max;
}
function getSmallestValue() public pure returns (ActionChoices) {
return type(ActionChoices).min;
}
}
笔记
枚举也可以在文件级别声明,在合约或库定义之外。