DEV Community

Loading Blocks
Loading Blocks

Posted on

Solidity Structs

1. Beyond Simple Data Organization

  • Challenge: managing related but different types of data (e.g., string name, address wallet, uint balance).
  • Naive approach: multiple mappings or arrays → messy and hard to maintain.

    Solution: structs = custom types that combine multiple fields into one logical unit.

  • Structs are not just containers, but powerful data modeling tools.


2. Trick 1

  • When accessing a mapping with struct values, if the key was never set:

    • Solidity does not throw an error.
    • Instead, it returns a default-initialized struct.
  • Default values:

    • string → empty string ""
    • address0x0...0
    • uint0
  • This allows an upsert pattern:

    • No need for if (exists) checks.
    • Directly assign values whether it’s the first time or an update.
  • Benefit: simplifies logic, merges create + update into one unified operation.


3. Trick 2

  • Structs can include:

    • basic types (string, uint),
    • other structs,
    • dynamic arrays
  • Example:

struct Person {
    string name;
    address addr;
    uint balance;
    Person[] friends;
}
Enter fullscreen mode Exit fullscreen mode

you can push another Person into the friends array.

Enables building on-chain relationship graphs, e.g., social networks.

Core insight: struct composition makes advanced modeling possible (nested structs, graphs, linked data).


4. Trick 3

In functions, struct variables must specify data location (memory or storage).

Omit it → compilation error.

Two initialization methods:

  1. Positional Initialization (compact but order-dependent):

    Person memory p = Person("Tim", msg.sender, msg.value);

  2. Key-Value Initialization (verbose but flexible):

Person memory p = Person({
    name: _name,
    addr: msg.sender,
    balance: msg.value
});
Enter fullscreen mode Exit fullscreen mode

Rules:

All fields must be provided.

Both methods enforce complete initialization → prevents partially defined structs.


5. Conclusion

Structs in Solidity go far beyond simple aggregation

Key powers:

Default struct behavior enables elegant upsert patterns.

Self-referencing arrays allow building complex graph structures.

Strict but flexible initialization rules balance readability and safety.

Together, these form the foundation of clear, rigorous, and powerful on-chain data architectures.

Top comments (0)