What is enum in Solidity: Definition and Usage
enum in Solidity is a way to create a custom type with a fixed set of named values, making code easier to read and manage. It helps represent a group of related states or options clearly within smart contracts.How It Works
Think of an enum as a list of named options, like choosing a flavor of ice cream from a menu. Instead of using numbers or strings that can be confusing, enum lets you use clear names to represent different states or choices.
In Solidity, when you define an enum, the compiler assigns each name a number starting from zero. This makes it easy to store and compare these values efficiently inside your smart contract.
Using enum improves code clarity and reduces errors because you only allow specific, predefined values instead of any random number or string.
Example
This example shows how to define an enum for traffic light colors and use it to set and check the current state.
pragma solidity ^0.8.0; contract TrafficLight { enum Light { Red, Yellow, Green } Light public currentLight; constructor() { currentLight = Light.Red; // Start with Red light } function changeLight() public { if (currentLight == Light.Red) { currentLight = Light.Green; } else if (currentLight == Light.Green) { currentLight = Light.Yellow; } else { currentLight = Light.Red; } } function getLight() public view returns (string memory) { if (currentLight == Light.Red) return "Red"; if (currentLight == Light.Yellow) return "Yellow"; return "Green"; } }
When to Use
Use enum when you have a variable that should only hold one value from a small set of options. This is common for states, modes, or categories.
For example, you can use enum to represent:
- Stages of a process (e.g., Pending, Active, Completed)
- Roles of users (e.g., Admin, User, Guest)
- Options in a menu or configuration
This helps prevent invalid values and makes your smart contract easier to understand and maintain.
Key Points
- Enums define a custom type with fixed named values.
- Each enum value is stored as a number starting from zero.
- They improve code readability and safety by limiting allowed values.
- Useful for representing states, roles, or options in contracts.