VOOZH about

URL: https://www.geeksforgeeks.org/solidity/solidity-enums-and-structs/

⇱ Solidity - Enums and Structs - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Solidity - Enums and Structs

Last Updated : 8 Jun, 2022

Enums are the way of creating user-defined data types, it is usually used to provide names for integral constants which makes the contract better for maintenance and reading. Enums restrict the variable with one of a few predefined values, these values of the enumerated list are called enums. Options are represented with integer values starting from zero, a default value can also be given for the enum. By using enums it is possible to reduce the bugs in the code.

Syntax:

enum <enumerator_name> { 
 element 1, element 2,....,element n
} 

Example: In the below example, the contract Types consist of an enumerator week_days,and functions are defined to set and get the value of a variable of the typeenumerator.

Output : 

👁 Enums

Struct

Structs in Solidity allows you to create more complicated data types that have multiple properties. You can define your own type by creating a struct.

They are useful for grouping together related data.

Structs can be declared outside of a contract and imported in another contract. Generally, it is used to represent a record. To define a structure struct keyword is used, which creates a new data type. 

Syntax:

struct <structure_name> { 
 <data type> variable_1; 
 <data type> variable_2; 
}

For accessing any element of the structure, 'dot operator' is used, which separates the struct variable and the element we wish to access. To define the variable of structure data type structure name is used.

Example: In the below example, the contract Test consists of a structure Book, and functions are defined to set and get values of the elements of the structure.

Output : 
 

👁 Structs

Comment
Article Tags:

Explore