Structs & Enums
Structs let you group related data under a custom type. Combined with mappings and arrays, they form the backbone of most contract data models — from NFT metadata to DeFi position tracking.
Structs in Practice
Structs group related fields into a named type.
- Can contain any Solidity type including other structs and arrays
- Cannot contain itself (recursive structs not allowed at the same level)
- Stored in storage, memory, or calldata depending on context
Storage packing: Solidity packs consecutive fields that fit into 32 bytes.
Place smaller types together to save gas:
- uint128, uint128 → 1 storage slot (32 bytes)
- uint128, uint256 → 2 storage slots (wasted gap between them)Common Mistakes
- Not packing struct fields — failing to arrange fields to minimize storage slots can double or triple deployment and call gas costs for storage-heavy contracts.
- Returning a storage struct pointer from a public function — always return memory copies from view functions; returning storage references creates unintended mutation paths.
- Using too many enum values — enums are uint8 internally (max 256 values). Trying to add a 257th value is a compile error.
- Comparing enums without casting — you can directly compare enum values (status == Status.Active), but passing them to external ABIs requires casting to uint8.
Tip
Tip
Practice Structs Enums in small, isolated examples before integrating into larger projects. Breaking concepts into small experiments builds genuine understanding faster than reading alone.
Once deployed, smart contracts are immutable — code is law
Practice Task
Note
Practice Task — (1) Write a working example of Structs Enums from scratch without looking at notes. (2) Modify it to handle an edge case (empty input, null value, or error state). (3) Share your solution in the Priygop community for feedback.
Quick Quiz
Common Mistake
Warning
A common mistake with Structs Enums is skipping edge case testing — empty inputs, null values, and unexpected data types. Always validate boundary conditions to write robust, production-ready web3 code.
Key Takeaways
- Structs let you group related data under a custom type.
- Not packing struct fields — failing to arrange fields to minimize storage slots can double or triple deployment and call gas costs for storage-heavy contracts.
- Returning a storage struct pointer from a public function — always return memory copies from view functions; returning storage references creates unintended mutation paths.
- Using too many enum values — enums are uint8 internally (max 256 values). Trying to add a 257th value is a compile error.