This section explains how to write struct in Solidity.
Syntax
Here is how to write the struct (structure) in Solidity.
The contents of a struct are a set of data type and variable name that defines the variable.
struct structure name {
data type 1 variable name 1;
data type 2 variable name 2;
data type n variable name n;
}
Sample Code
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.17;
contract Test {
// Structure
struct User {
string name;
uint age;
address wallet;
}
User[] public users;
function addUser(string memory _name, uint _age, address _wallet) public {
User memory newUser = User({
name: _name,
age: _age,
wallet: _wallet
});
users.push(newUser);
}
function getUser(uint _index) public view returns (string memory, uint, address) {
User memory user = users[_index];
return (user.name, user.age, user.wallet);
}
}
struct (structure) are used when you want to handle multiple variables together. In the sample code, since I want to manage the name/age/wallet address of each user, I do not define variables individually, but treat them as a single variable by using the structure User.