先來一段代碼:
// SPDX-License-Identifier: GPL-3.0
pragma solidity >=0.4.16 <0.9.0;
contract test{
? ? enum ActionChoices{Goleft,GoRight,GoStraight,GoStill}
? ? ActionChoices choice;
? ? ActionChoices constant defaultChoice = ActionChoices.Goleft;
? ? function setGoStraight() public {
? ? ? ? choice = ActionChoices.GoStraight;
? ? }
? ? function setGoStill() public {
? ? ? ? choice = ActionChoices.GoStill;
? ? }
? ? //由于枚舉類型不屬于|ABI|的一部分晓勇,因此對于氖來自solidity外部調(diào)用,
? ? //getChoice 的簽名會自動被改為getChoice() returns(uint8);
? ? function getChoice() public view returns(ActionChoices){
? ? ? ? return choice;
? ? }
? ? function getDefaultChoise() public pure returns(uint){
? ? ? ? return uint(defaultChoice);
? ? }
}
一疾宏、枚舉定義
? ? enum ActionChoices{Goleft,GoRight,GoStraight,GoStill}
二黍特、設(shè)置默認(rèn)值
? ? ActionChoices constant defaultChoice = ActionChoices.Goleft;
三、定義四個(gè)方法薪丁,兩個(gè)設(shè)置遇西,一個(gè)是獲得當(dāng)前狀態(tài),一個(gè)是默認(rèn)狀態(tài)严嗜;
獲得默認(rèn)狀態(tài)的粱檀,不會由被設(shè)置了而改變;
由于默認(rèn)設(shè)置為goLeft,所以GetDefaultChoice時(shí)總是顯示枚舉的第0個(gè)的內(nèi)容漫玄;
這個(gè)跟大多數(shù)語言一樣茄蚯,都是從0開始編碼的。所有即使設(shè)置了goStill了睦优,在getChoice時(shí)顯示為3渗常;