Structs are custom data types that allow developers to group together multiple variables under one name. Unlike arrays, which store elements of the same type, structs can hold multiple types of data in a single structure.
Structs are useful for representing complex data entities, such as user profiles, transactions, orders, and metadata, making it easier to manage and organize data within a program.
A struct is composed of fields, each with its own data type and name. The key components are:
The code block below shows a Person
struct with three fields: name
, age
, and wallet
. Each field has a specific data type that determines the kind of data it can store.
/ Struct Name
struct Person {
// Fields and Data Types
string name; // Data Type: String | Field: name
uint256 age; // Data Type: Unsigned Integer (256 bits) | Field: age
address wallet; // Data Type: Ethereum Address | Field: wallet
}
Initialize the struct: A new Person instance is created using the new keyword and its fields are initialized.
// Create a new Person instance using the `new` keyword and initialize its fields
Person memory person = new Person({
name: "John Doe",
age: 30,
address: 0x1234567890123456
});
Accessing fields: Fields in a struct are accessed using dot notation (e.g., person.name).
//Accessing fields using dot notation
string name = person.name; // "John Doe"
uint256 age = person.age; // 25
address wallet = person.wallet; // 0x1234567890123456
A visual representation of the struct
Structs (or similar structures) are widely used across traditional programming languages like C, C++, and Python (classes) and in smart contract development languages.
Each language has its own syntax for defining structs, but the core concept remains the same.
Structs can store a wide range of data types, including addresses, integers, strings, and more. The specific fields included in a struct depend on the contract's use case.
User profiles (Solidity)
struct UserProfile {
string username;
address userAddress;
uint256 reputation;
}
Token metadata (Move)
public struct TokenMetadata {
token_name: vector<u8>,
token_id: u64,
token_symbol: vector<u8>,
} has copy, drop, store
Transaction data (Rust)
struct Transaction {
tx_id: u32,
sender: String,
receiver: String ,
}
Voting ballots (Vyper)
struct Ballot {
voterAddress: address
voteWeight: uint256
hasVoted: bool
}
Employee Records (Cairo)
struct Employee {
age: u8,
id: u32,
role: felt252,
}
If you’re interested in learning how to build structs in Solidity, Cyfrin Updraft can teach you how!