Structs, Arrays, and Mapping in Solidity

In this lesson, you'll learn about fundamental data structures in Solidity: structs, arrays, and mappings. These structures are crucial for organizing and managing data within your smart contracts, enabling you to build more complex and functional decentralized applications.

Learning Objectives

  • Define and use structs to create custom data types.
  • Understand the difference between fixed-size and dynamic arrays and how to use them.
  • Implement mappings to store and retrieve data associated with unique keys.
  • Apply these data structures in simple Solidity contracts.

Lesson Content

Introduction to Data Structures

Data structures are fundamental building blocks for organizing and storing data efficiently. In Solidity, you'll primarily use structs, arrays, and mappings to manage the information your smart contracts interact with. These structures allow you to represent complex data in a structured manner, making your code easier to read, write, and maintain.

Quick Check: Which keyword is used to define a custom data type in Solidity that groups related variables?

Structs: Creating Custom Data Types

Structs allow you to create custom, composite data types that group related variables. Think of them as blueprints for creating objects with specific properties.

Example:

pragma solidity ^0.8.0;

struct Person {
    string name;
    uint age;
    address walletAddress;
}

contract StructExample {
    Person public john;

    function createPerson(string memory _name, uint _age, address _walletAddress) public {
        john = Person(_name, _age, _walletAddress);
    }

    function getPersonName() public view returns (string memory) {
        return john.name;
    }
}

In this example, Person is a struct containing a name, age, and walletAddress. We then declare a john variable of type Person and a function to initialize the struct.

Quick Check: What is the primary difference between a fixed-size array and a dynamic array?

Arrays: Storing Ordered Collections of Data

Arrays in Solidity are ordered collections of elements of the same data type. You can have fixed-size arrays (size defined at compile time) and dynamic arrays (size can change at runtime).

Fixed-Size Array Example:

pragma solidity ^0.8.0;

contract FixedArrayExample {
    uint[3] public numbers;

    function setNumbers() public {
        numbers[0] = 1;
        numbers[1] = 2;
        numbers[2] = 3;
    }

    function getNumberAtIndex(uint _index) public view returns (uint) {
        return numbers[_index];
    }
}

Dynamic Array Example:

pragma solidity ^0.8.0;

contract DynamicArrayExample {
    uint[] public numbers;

    function addNumber(uint _number) public {
        numbers.push(_number);
    }

    function getArrayLength() public view returns (uint) {
        return numbers.length;
    }
}

In this example, the numbers array is dynamically sized, and we use the push() function to add elements. Dynamic arrays use .length property to find the array's length.

Quick Check: What is the key-value pair used in Solidity called?

Mappings: Key-Value Data Storage

Mappings are like dictionaries or hash tables. They associate a key with a value. The key can be any primitive data type (e.g., uint, address, string) or a bytes type, and the value can be any data type, including structs and arrays.

Example:

pragma solidity ^0.8.0;

contract MappingExample {
    mapping(address => uint) public balances;

    function setBalance(address _account, uint _amount) public {
        balances[_account] = _amount;
    }

    function getBalance(address _account) public view returns (uint) {
        return balances[_account];
    }
}

In this example, balances is a mapping where the key is an address (representing an account) and the value is a uint (representing the balance). Mappings, unlike arrays, don't have a .length property. Also, mappings are considered initialized for all possible keys. If you try to read a value from a non-existent key, the default value for the value's type will be returned (0 for uint, false for bool, etc.).

Quick Check: How do you add an element to a dynamic array in Solidity?

Best Practices and Considerations

When working with data structures, consider these best practices:

  • Gas Efficiency: Be mindful of gas costs, especially when dealing with large arrays. Operations on dynamic arrays and complex structs can be expensive.
  • Immutability: Data stored in a smart contract is generally immutable. Plan how you want to handle changes to your data carefully.
  • Security: Ensure proper access control to prevent unauthorized modification of your data. Use appropriate visibility modifiers (public, private, internal) appropriately.

Quick Check: Which of the following is NOT true about mappings?

Progress
0%