Working with struct and enum
There are several elementary types in solidity that can be used together to form various complex user-defined types. In this recipe, you will learn about two user-defined types in Solidity: struct
and enum
.
How to do it...
Let's create and work with various user-defined types using struct
and enum
.
Structs
Structs provide a way to define new types of solidity:
- Use the
struct
keyword for creating user-defined types in solidity:
struct Person { }
- Create a
struct
with a name and the associated properties inside it:
struct Person { uint16 id; bytes32 fName; bytes32 lName; }
- Structs can also include
arrays
,mapping
, or other user-defined types:
struct Person { uint16 id; bytes32 fName; bytes32 lName; Contact phone; } struct Contact { uint countryCode; uint number; }
You cannot create a
struct
member with its own type. This helps in limiting the size of the struct to a finite value.- Create a variable of the
struct
type as follows:
Person owner...