Skip to content
Back to Curriculum
FUNDAMENTALS

Structs & Enums

Structs allow you to group related data together (like a `class` without methods). Enums allow you to define a custom type with a limited set of constant values (like states).

Syntax Structure

Example.sol
Loading...

Key Components

  • Boilerplate structure required by the Solc compiler.
  • Placement of state variables versus functions.

Practical Implementation

Using a Struct to pack data efficiently into storage slots.

Practical.sol
Loading...

Core Concepts

Packing

Arranging struct members to fit into 32-byte slots reduces gas costs drastically.

Enum

Under the hood, just a uint8 (0, 1, 2...). Makes code readable.

Storage Pointer

Pass structs by `storage` reference to modify them in place.

Mental Model

The Custom Container

A **Struct** is a custom box. You decide exactly what fits inside. If you pack the items neatly (small items next to each other), you can fit the whole box into a single 'Storage Slot' shelf space, saving massive rent (gas).

Under the Hood

Enums are `uint8` by default. Structs are laid out sequentially. If items fit in 32 bytes, they share a slot (`SSTORE` writes to the same key).

MLOADMSTORESSTORESLOAD

Gas Analysis

Struct packing is the easiest way to save gas.

  • • Order `uint`s from smallest to largest or group them to sum to 256 bits.
  • • Put `uint256` members last if possible, or isolate them.
  • • Use `enum` instead of strings for states.

Security Risks

Structs in memory are not packed tightly like in storage.

  • ! Assuming memory structs are packed can lead to incorrect hash calculations (`keccak256(abi.encode(myStruct))`).

Common Use Cases

Struct: Representing a 'User', 'Campaign', or 'Transaction'.
Enum: Tracking state ('Pending', 'Active', 'Canceled').

Interactive Visualization

See exactly how the EVM handles this code in memory, storage, and the stack.

Interactive Simulation
0 / 0
Loading...
Type Solidity code (v0.8.26) and click Run. Compiler loads on first use (~2MB).

Click Run to execute the simulation

Then use the step controls to navigate