Struct in Solidity smart contracts

Structs are custom data types that can group several variables. They represent a record of “something”. Suppose you want to keep a list of “To Do’s” and need to know if they are completed. One would keep a simple list and create a Struct:

  • item “To Do”
  • was it completed?

See the contract below for an example of how to create a “To Do” Struct

Contract Todos {

//create a custom struct called Todo

Struct Todo {
       String text;
       Bool completed;
       }

//below we created a data type of Todo which is the struct to create an array

Todo[] public todos; 

Function create (string memory _text) public {
//Push a new todo struct into the array
    Todos.push(Todo(_text, false));  

Function get(uint _index) public view returns (string memory, bool) {
    Todo storage todo = todos[_index];
//this is how you get information out of a struct state variable
    Return (todo.text, todo.completed); 

Try it in Remix

For more information read the docs.

This code is for learning and entertainment purposes only. The code has not been audited and use at your own risk. Remember smart contracts are experimental and could contain bugs.

Click here for more information about how to use the Ethereum test network and how to obtain test ETH.

Next Review – Payable Function in Solidity smart contracts

1 thought on “Struct in Solidity smart contracts

Leave a Reply