OSSolidity.007: Solidity Structs — Record Types, Storage References and Memory Copies

Conceptual oil painting of grouped data records and persistent storage versus temporary memory.

Open-Source Solidity Programming • Intermediate • Estimated study time: 40 minutes.

A struct defines a custom record type by grouping named fields that belong together. Unlike a mapping, which selects a value by key, a struct describes the shape of each value. Combining both lets a smart contract associate an account with several related properties. The preceding Solidity mappings lesson introduced keyed storage and presence checks; the laboratory extends those ideas to structured records.

Prerequisites and learning objectives

Review contract structure and Remix, value types and data locations, and function visibility and mutability. By completion, learners should be able to declare and initialize a struct, store records in a mapping, distinguish storage references from memory copies, handle absent and deleted records, and test account isolation. Use only a disposable local Remix VM. Never deploy the teaching contract to a public network, use real funds, or enter private telemetry.

Declaring and initializing a record

The Solidity language reference defines structs as user-defined types. A declaration names the type and its fields; it does not create a persistent record on its own. Field names identify members with dot notation. For example, the following declaration groups a numerical measurement and a presence flag:

struct Device {
    uint256 reading;
    bool exists;
}

A mapping from an address to Device supplies a record for each address. An unwritten key produces default values: zero for the integer and false for the Boolean. A valid measurement may also equal zero, so the Boolean carries distinct information. Named initialization makes the correspondence between fields and values explicit.

Dapp University introduces Solidity fundamentals in English, including mappings at 08:21 and structs at 09:43. Watch at source.

Laboratory: a per-account record registry

Open Remix, create LabRegistry.sol, select a compatible Solidity 0.8.x compiler at or above 0.8.24, and use a local Remix VM in the Deploy & Run Transactions panel. Select the matching contract, compile it and deploy without Ether. The following complete example maintains a separate record for each caller:

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;
 
contract LabRegistry {
    struct Device {
        uint256 reading;
        bool exists;
    }
 
    mapping(address => Device) private devices;
 
    function register(uint256 reading) external {
        require(!devices[msg.sender].exists, "Already registered");
        devices[msg.sender] = Device({
            reading: reading,
            exists: true
        });
    }
 
    function updateReading(uint256 reading) external {
        Device storage record = devices[msg.sender];
        require(record.exists, "Missing device");
        record.reading = reading;
    }
 
    function preview(uint256 reading)
        external view returns (Device memory)
    {
        Device memory copy = devices[msg.sender];
        require(copy.exists, "Missing device");
        copy.reading = reading;
        return copy;
    }
 
    function read(address account)
        external view returns (uint256, bool)
    {
        Device storage record = devices[account];
        return (record.reading, record.exists);
    }
 
    function remove() external {
        delete devices[msg.sender];
    }
}

The register function writes a new record for msg.sender and rejects duplicate registration. The updateReading function selects the caller’s existing record and modifies one field without replacing its presence flag. The read function accepts any account and returns two separate scalar values. A private mapping restricts direct Solidity-level access from other contracts; it does not encrypt blockchain storage. Anyone can inspect public-chain state, and the read function deliberately exposes the fields.

Storage reference versus memory copy

The data-location assignment rules explain why the two update operations behave differently. A local storage reference aliases existing persistent data. Assigning through record.reading changes the mapping value. Copying from storage into memory instead creates independent data for the duration of the call. The preview function modifies only its copy and returns the proposed record without changing persistent state. Memory-to-memory assignments can alias one another; the independence here specifically follows from the storage-to-memory copy.

Smart Contract Programmer explains storage, memory and calldata in English, including how reference types use different data locations. Watch at source.

Verification procedure

Start with account A and a freshly deployed instance. Call read(A) and expect (0, false). Register a reading of 24 using A, then read(A) and expect (24, true). Call preview(99) and expect a returned record containing 99 and true. Read A again and expect (24, true), proving that the preview did not change persistent storage. Call updateReading(30) and expect read(A) to return (30, true). A second registration by A should revert.

Switch to account B. Before registration, read(B) should return (0, false), and updateReading(1) should revert. Register B with 0 and verify (0, true), demonstrating that a zero measurement can be present. Read A and confirm (30, true). Switch to A and call remove; read(A) should return (0, false) while B remains (0, true). Expected outputs are derived from the language rules. The compiler and EVM runtime were unavailable during editorial preparation, so compilation and execution remain learner verification steps rather than completed tests.

Engineering limitations

Deleting the simple record restores default values for both fields. A mapping cannot enumerate its own keys; an iterable registry needs an additional index and a deletion strategy. Avoid loops over unbounded state in transactions because gas consumption may eventually exceed practical limits. The laboratory uses only scalar fields; structs containing mappings have additional storage restrictions and deletion considerations. A production registry also needs explicit authorization policies, validated units, appropriate events and independent security review. The example accepts arbitrary integer readings and is not a calibrated monitoring system.

Exercises and answer key

Exercise 1: Add a view function named exists(address account) returning a Boolean. Exercise 2: Predict the outcome of assigning 100 to a memory copy and then reading the original record. Exercise 3: Explain why zero cannot act as the absence sentinel. Exercise 4: Explain how msg.sender prevents one caller from using updateReading to modify another caller’s key. Exercise 5: Add a delete operation limited to the caller and explain why the original record can be registered again afterward.

Answers: 1. Return devices[account].exists from a view function. 2. The original reading is unchanged because the copy is independent of storage. 3. Zero can be valid measured data. 4. The function derives the mapping key from the calling account rather than accepting an arbitrary address. 5. The existing remove function implements the requested behavior; deleting the scalar record restores exists to false, satisfying the registration guard.

Conclusion

Structs organize related fields, mappings supply keyed access, and storage references permit deliberate persistent mutation. Use memory copies for isolated calculations and previews. Always distinguish an absent record from a valid default-valued record and verify state transitions under multiple accounts before considering deployment.

Editor’s Note: We volunteer daily to ensure the credibility of the information on this platform is Verifiably True. If you would like to support to help further secure the integrity of our research initiatives, please scan the QR code below

BitcoinVersus.Tech donation QR code for 5,000 satoshis

For mobile scanning, open the article on another display and scan the QR code with a Bitcoin wallet. The voluntary donation amount is 5,000 sats. Verify the receiving address 3C9o19EH5HSiwEPyCTmEKzxhNCbo2X6TTb before sending.

BitcoinVersus.Tech publishes technology and financial journalism for informational purposes and does not provide financial, investment, or legal advice.

Leave a Reply