枚舉

2022-05-11 18:06 更新

枚舉是在 Solidity 中創(chuàng)建用戶定義類型的一種方式。它們可以顯式轉(zhuǎn)換為所有整數(shù)類型,但不允許隱式轉(zhuǎn)換。整數(shù)的顯式轉(zhuǎn)換在運(yùn)行時檢查該值是否在枚舉范圍內(nèi), 否則會導(dǎo)致Panic 錯誤。枚舉至少需要一個成員,聲明時它的默認(rèn)值是第一個成員。枚舉不能有超過 256 個成員。

數(shù)據(jù)表示與 C 中的枚舉相同:選項由從 開始的后續(xù)無符號整數(shù)值表示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;
    }
}

筆記

枚舉也可以在文件級別聲明,在合約或庫定義之外。


以上內(nèi)容是否對您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號
微信公眾號

編程獅公眾號