Structs y enums
Modele datos complejos en Solidity mediante tipos de struct personalizados y represente conjuntos fijos de estados con enums.
Structs y enums es una lección gratuita de Blockchain Smart Contracts with Solidity en CoddyKit. Esta es la lección 4 de 4. Puedes leer la lección completa abajo gratuitamente — luego la practicas en el navegador con un editor de código integrado y un tutor de IA 24/7. Forma parte de la ruta de aprendizaje de Blockchain Smart Contracts with Solidity, y tu progreso se sincroniza en la web y la app de CoddyKit. El curso de Blockchain Smart Contracts with Solidity incluye 4 lecciones en total.
Partes de esta lección aún no han sido traducidas y se muestran en 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.
Preguntas frecuentes
¿La lección «Structs y enums» es gratis?
Sí — el texto completo de «Structs y enums» es gratis para leer aquí en la web. Para practicarla de forma interactiva (editor de código integrado y tutor de IA 24/7) y desbloquear el resto del curso de Blockchain Smart Contracts with Solidity, actualiza a CoddyKit PRO. El curso de Blockchain Smart Contracts with Solidity incluye 4 lecciones en total.
¿Qué aprenderé en «Structs y enums»?
Modele datos complejos en Solidity mediante tipos de struct personalizados y represente conjuntos fijos de estados con enums. Practicas Blockchain Smart Contracts with Solidity con código real que ejecutas directamente en el navegador, y un tutor de IA 24/7 responde tus preguntas mientras trabajas en la lección.
¿Necesito experiencia previa para empezar Blockchain Smart Contracts with Solidity?
No se requiere experiencia previa. Blockchain Smart Contracts with Solidity en CoddyKit está estructurado para principiantes hasta estudiantes avanzados, así que puedes empezar aquí o desde el inicio y avanzar a tu ritmo. Esta es la lección 4 de 4.
¿Cuánto tiempo toma la lección «Structs y enums»?
La mayoría de las lecciones de CoddyKit toman alrededor de 5–10 minutos. Cada una es compacta e interactiva, así que avanzas constantemente y retomas exactamente por donde dejaste en la web y la app.
¿Puedo escribir y ejecutar código en esta lección de Blockchain Smart Contracts with Solidity?
Sí. Cada lección de Blockchain Smart Contracts with Solidity incluye un editor de código integrado, así que escribes y ejecutas código real directamente en tu navegador y obtienes retroalimentación instantánea de IA — sin configuración local necesaria.
Todas las lecciones de este curso
- Tipos de datos y variables en Solidity
- Estructuras de control y bucles
- Funciones y modificadores de visibilidad
- Structs y enums