Understanding Structs in solidity

0
25

Defining custom types in Solidity is made possible with Struct. It can have group of several variables.

You can check the reference documentation in official documentation of solidity @ https://docs.soliditylang.org/en/v0.6.8/types.html?highlight=struct#structs

Example:

struct User {
uint level;
uint status;
}
mapping(address => User) public userList;
User userDetail = User(1, 1);
function updateUserLevel(uint userLevel) public { 
userDetail.level = userLevel;
}
function getUserDetail(address userAddress) public returns (User memory) {
return userList[userAddress];
}

Full working example of the code can be found @ here .

In the above example, we have created a struct User and have used to create variable userDetail using User as type and also used it as type of variable.

We have used keyword struct to define struct datatype in Solidity, along with is the name of struct and variable names defined in the curly braces.

struct StructName {
string name;
uint value;
}

In above code we have defined struct in line `User userDetail = User(1, 1);` which is the shortest way to define struct.

We can define struct in other ways as well.

function createUserRecord (address userAddress_, uint level_, uint status_) public {
User storage newRecord = userList[userAddress];
newRecord.level = level_;
newRecord.status = status_;
}
function createUserRecordTwo (address userAddress_, uint level_, uint status_) public {
userList[userAddress_] = User({
level : level_, status : status_
});
}

So, the above are two more ways to use struct and create object, and is set in userListmapping (that we will see in another tutorial).

Note: Full code sample with structs can be found here StructExampleFull.sol

There are few limitations in using Struct,

  • function cannot return struct data unless its internal function call
  • struct cannot be recursive ie. same struct type inside the struct
struct User {
uint level;
uint status;
User refererUser; // this will return error since recursive
}

Understanding Structs in solidity was originally published in Coinmonks on Medium, where people are continuing the conversation by highlighting and responding to this story.