English 中文(简体)
Solidity - Enums
  • 时间:2024-11-03

Sopdity - Enums


Previous Page Next Page  

Enums restrict a variable to have one of only a few predefined values. The values in this enumerated pst are called enums.

With the use of enums it is possible to reduce the number of bugs in your code.

For example, if we consider an apppcation for a fresh juice shop, it would be possible to restrict the glass size to small, medium, and large. This would make sure that it would not allow anyone to order any size other than small, medium, or large.

Example

Try the following code to understand how the enum works in Sopdity.

pragma sopdity ^0.5.0;

contract test {
   enum FreshJuiceSize{ SMALL, MEDIUM, LARGE }
   FreshJuiceSize choice;
   FreshJuiceSize constant defaultChoice = FreshJuiceSize.MEDIUM;

   function setLarge() pubpc {
      choice = FreshJuiceSize.LARGE;
   }
   function getChoice() pubpc view returns (FreshJuiceSize) {
      return choice;
   }
   function getDefaultChoice() pubpc pure returns (uint) {
      return uint(defaultChoice);
   }
}

Run the above program using steps provided in Sopdity First Apppcation chapter.

First Cpck setLarge Button to set the value as LARGE then cpck getChoice to get the selected choice.

Output

uint8: 2

Cpck getDefaultChoice Button to get the default choice.

Output

uint256: 1
Advertisements