89DEVs

struct data type in Solidity

The struct data type in Solidity allows us to store data of different data types in a structured way. For example we can build a library of books where each book has different attributes like title, author and a book id. The title and author could be string types while the book id is a uint data type.

declare struct

To declare a struct we simply use the struct keyword within our contract. In the example below we create a struct of our book library. Our struct here can hold a uint data type named bookId, a string data type named title and another string data type named author. // define a struct in Solidity struct Books { uint id; string title; string author; }

create struct

After we have declared the struct Books we can now create the first book by passing the arguments. We have also declared a state variable named _booktitle as public string. After we have created the first book, we assign the title to the state variable _booktitle by accessing struct via dot notation. string public _booktitle; function createBook() external { Books memory book1 = Books(1, 'Learn Solidity', '89DEVs'); _booktitle = book1.title; }

update struct

To update values in our struct we can just assign new values via the dot notation of our struct. In the example below we rename the book title of the previous example from Learn Solidity to Learn Web3. The next read operation will then return the new title value. // rename struct values book1.title = 'Learn Web3';

delete struct

We can also delete a struct by using the delete keyword. After the struct is deleted it is removed from memory and we can't access it anymore. // delete struct in Solidity delete book1;

array of struct

A common practice is to create an array and push new struct objects into the array to have a collection of all struct objects. Let's see the example below to understand how it works. Books[] books; function foo() external { books.push(Books(1, 'Learn Solidity', '89DEVs')); } The array books is created as state variable and within the function foo() we create a new struct object and push it into the array. This gives us a collection of structs.

        

Summary

Click to jump to section