Structs e Enums
Modele dados complexos em Solidity usando tipos personalizados de struct e represente conjuntos fixos de estados com enums.
Structs e Enums é uma aula grátis de Blockchain Smart Contracts with Solidity no CoddyKit. Esta é a aula 4 de 4. Você pode ler a aula completa abaixo gratuitamente — depois pratica ao vivo no navegador com um editor de código integrado e um tutor de IA 24/7. Faz parte do caminho de aprendizado de Blockchain Smart Contracts with Solidity, e seu progresso é sincronizado entre a web e o app CoddyKit. O curso de Blockchain Smart Contracts with Solidity inclui 4 aulas no total.
Partes desta aula ainda não foram traduzidas e aparecem em inglês.
Why Custom Types?
Beyond primitives like uint and address, Solidity lets you define your own types. Structs group related fields, and enums represent a fixed set of named states.
Declaring a Struct
A struct bundles several variables under one name, perfect for modeling real-world entities like a user or an order.
struct User {
string name;
uint age;
address wallet;
}Creating Struct Instances
You can construct a struct by positional arguments or by naming each field. Named arguments are clearer and less error prone.
User memory u = User({
name: "Alice",
age: 30,
wallet: msg.sender
});Structs in Storage vs Memory
A struct in storage persists on chain; in memory it is a temporary copy. Assigning a storage struct to a memory variable copies it, so changes do not write back.
Updating Struct Fields
To modify persisted data, work with a storage reference and assign to its fields directly.
User storage u = users[msg.sender];
u.age = 31;Structs Inside Mappings
Structs shine when stored in a mapping keyed by address or id, giving each user their own record.
mapping(address => User) public users;
users[msg.sender] = User("Bob", 25, msg.sender);Declaring an Enum
An enum defines a small set of named options. It improves readability over raw numbers for representing state.
enum Status { Pending, Shipped, Delivered, Cancelled }Using Enum Values
Enum members are stored as uint starting at 0. You compare and assign them by name, which makes contract logic self-documenting.
Status public status = Status.Pending;
function ship() public {
status = Status.Shipped;
}Enums in State Machines
Enums are ideal for modeling a state machine. Guard transitions with require so an order can only move to a valid next state.
function deliver() public {
require(status == Status.Shipped, "Not shipped yet");
status = Status.Delivered;
}Combining Structs and Enums
Put an enum field inside a struct to track each record state, for example storing a Status on every order struct so each order tracks its own lifecycle.
Gas Considerations
Each struct field is a storage slot, and writing storage is expensive. Order fields to pack smaller types together, and use enums (one byte range) instead of strings for fixed states to save gas.
Quick Check
Check your structs and enums knowledge.
Recap
You learned Solidity custom types:
- Structs group related fields and are often stored in mappings
- Mind storage vs memory when copying or updating structs
- Enums model fixed states as integers and power state machines
- Combine them and pack fields to save gas
Custom types make contracts more expressive and maintainable.
Perguntas Frequentes
A aula “Structs e Enums” é grátis?
Sim — o texto completo de “Structs e Enums” é grátis para ler aqui na web. Para praticá-la interativamente (um editor de código integrado e um tutor de IA 24/7) e desbloquear o restante do curso de Blockchain Smart Contracts with Solidity, atualize para CoddyKit PRO. O curso de Blockchain Smart Contracts with Solidity inclui 4 aulas no total.
O que vou aprender em “Structs e Enums”?
Modele dados complexos em Solidity usando tipos personalizados de struct e represente conjuntos fixos de estados com enums. Você pratica Blockchain Smart Contracts with Solidity com código prático que executa diretamente no navegador, e um tutor de IA 24/7 responde suas dúvidas enquanto trabalha na aula.
Preciso ter experiência prévia para começar Blockchain Smart Contracts with Solidity?
Nenhuma experiência prévia é necessária. Blockchain Smart Contracts with Solidity no CoddyKit é estruturado para alunos iniciantes até avançados, então você pode começar aqui ou desde o início e aprender no seu ritmo. Esta é a aula 4 de 4.
Quanto tempo leva a aula “Structs e Enums”?
A maioria das aulas CoddyKit leva cerca de 5–10 minutos. Cada uma é compacta e interativa, então você faz progresso constante e retoma exatamente de onde parou entre web e app.
Posso escrever e executar código nesta aula de Blockchain Smart Contracts with Solidity?
Sim. Cada aula de Blockchain Smart Contracts with Solidity inclui um editor de código integrado, então você escreve e executa código real direto no navegador e recebe feedback de IA instantaneamente — nenhuma configuração local necessária.
Todas as aulas deste curso
- Tipos de dados e variáveis em Solidity
- Estruturas de controle e loops
- Funções e modificadores de visibilidade
- Structs e Enums