Loading...
Structures in solidity are similar to structs in other languages.
It is possible to define custom data type in solidity like other programming languages
In this smartbook we are going to see how we can use struct.
Struct is defined as struct keyword and name of struct.
The below snippet shows how to create custom data type using struct.
struct Task{
string text;
uint rollno;
bool Status;
}
We are going to store all the structs in the array.
The name of array is tasks and it is of type Task struct.
Task[]public tasks;
Then we defined function as create which is going to take inputs when we call it.Then it stores all the inputed parameters in array name called as task
function create(string memory _text,uint _rollno,bool _status)public{
tasks.push(Task(_text,_rollno,_status));
}
Now we want to dislpay the struct by the index number of the array.
Here Task is the type of variable (here it is struct type) and task is the state variable which is stored in storage as state variable.
We can access the struct member variables by dot operator.
function getStudent(uint _index)public view returns(string memory,uint,bool){
Task storage task=tasks[_index];
return (task.text,task.rollno,task.Status);
}
Note that we used storage to store the array of structs ,we can use the memory also but if we use memory then we can't change or modify the data.
In storage it is not going to copy whole struct it is just reffrence to storage and member data can be modify.
Below is the complete code and output:
pragma solidity >=0.8.1 < 0.9.0;
contract Student{
struct Task{
string text;
uint rollno;
bool Status;
}
Task[]public tasks;
function create(string memory _text,uint _rollno,bool _status)public{
tasks.push(Task(_text,_rollno,_status));
}
function getStudent(uint _index)public view returns(string memory,uint,bool){
Task storage task=tasks[_index];
return (task.text,task.rollno,task.Status);
}
}
Output:
After calling getStudent function we have to pass the index and we will get that particular struct.
Here 0th struct array is displayed.
0:
string: Raj
1:
uint256: 24
2:
bool: true