0Pricing
Blockchain Smart Contracts with Solidity · Lekcja

Mapowania i tablice dynamiczne

Implementuj złożone struktury danych, takie jak mapowania dla par klucz–wartość i tablice dynamiczne dla elastycznych list danych.

Mapowania i tablice dynamiczne to bezpłatna lekcja Blockchain Smart Contracts with Solidity na CoddyKit. To lekcja 2 z 4. Możesz przeczytać całą lekcję poniżej za darmo — a potem ćwiczyć ją interaktywnie w przeglądarce z wbudowanym edytorem kodu i tutorem AI dostępnym 24/7. To część ścieżki edukacyjnej Blockchain Smart Contracts with Solidity, a Twój postęp synchronizuje się między webem a aplikacją CoddyKit. Kurs Blockchain Smart Contracts with Solidity zawiera 4 lekcji w sumie.

Części tej lekcji nie zostały jeszcze przetłumaczone i są wyświetlane po angielsku.

Flexible Data Structures

Welcome! In Solidity, managing collections of data efficiently is key for complex smart contracts. Today, we'll dive into two powerful data structures: mappings and dynamic arrays.

These tools allow your contracts to store and retrieve information in flexible, scalable ways, essential for building robust decentralized applications.

What Are Mappings?

Think of a mapping like a dictionary or a hash table. It stores data as key-value pairs.

  • You provide a unique key (like an address or an ID).
  • The mapping returns the value associated with that key (like a user's balance or a name).
  • Keys are not stored, only their cryptographic hash, making them very efficient for lookups.

Declaring a Mapping

To declare a mapping, you specify the key type and the value type. It's usually declared as a public state variable.

Here's how you declare a mapping to store a uint (value) for each address (key):

pragma solidity ^0.8.0;

contract MyMappings {
    // A mapping from address to unsigned integer
    mapping(address => uint) public balances;

    // Another mapping: from uint ID to string name
    mapping(uint => string) public userNames;
}

Storing Data in Mappings

You can easily assign or update a value in a mapping using its key. If a key doesn't exist yet, it's created.

Let's add a function to update a user's balance:

pragma solidity ^0.8.0;

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

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

    // Try calling setBalance with your address and a number,
    // then check balances(yourAddress) in Remix.
}

Retrieving Data from Mappings

Accessing data is straightforward: just use the key. If you try to retrieve a value for a key that hasn't been set, Solidity returns the default value for that type (e.g., 0 for uint, empty string for string, address(0) for address).

pragma solidity ^0.8.0;

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

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

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

    // Deploy, call setBalance, then getBalance.
    // Try getBalance for an address not yet set.
}

What Are Dynamic Arrays?

A dynamic array is a list of elements of the same type, but unlike fixed-size arrays, its size can change at runtime. This makes them perfect for situations where you don't know the exact number of items upfront.

  • They can grow or shrink.
  • Elements are accessed by their index (starting from 0).
  • They are more gas-expensive than fixed-size arrays for storage.

Declaring Dynamic Arrays

To declare a dynamic array, you simply omit the size in the square brackets. You can declare them as state variables or local variables (using memory or calldata).

Here's an example of a dynamic array of uints:

pragma solidity ^0.8.0;

contract MyArrays {
    // A dynamic array of unsigned integers stored in state
    uint[] public numbers;

    // A dynamic array of strings (for memory use)
    function createNameList() public pure returns (string[] memory) {
        string[] memory names = new string[](0); // Initialize empty
        return names;
    }
}

Adding Elements to Dynamic Arrays

The most common way to add elements to a dynamic array is using the push() method. It appends a new element to the end of the array.

  • array.push(): Adds a zero-initialized element.
  • array.push(value): Adds a specific value.
pragma solidity ^0.8.0;

contract MyArrays {
    uint[] public numbers;

    function addNumber(uint _num) public {
        numbers.push(_num); // Add _num to the end
    }

    function addDefault() public {
        numbers.push(); // Add a 0 to the end
    }

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

Accessing & Removing Elements

You can access elements by their index (starting from 0). To remove elements, you can use pop(), which removes the last element and reduces the array's length.

pragma solidity ^0.8.0;

contract MyArrays {
    uint[] public data = [10, 20, 30, 40];

    function getElement(uint _index) public view returns (uint) {
        require(_index < data.length, "Index out of bounds");
        return data[_index];
    }

    function removeLast() public {
        data.pop(); // Removes 40
    }

    function getLength() public view returns (uint) {
        return data.length;
    }
}

Advanced: Mapping of Arrays

You can combine these structures! A common pattern is a mapping where the value type is a dynamic array. This lets you associate a list of items with a key, like a user's transaction history.

Here's an example of mapping an address to a dynamic array of uints:

pragma solidity ^0.8.0;

contract UserData {
    mapping(address => uint[]) public transactionHistory;

    function addTransaction(address _user, uint _amount) public {
        transactionHistory[_user].push(_amount);
    }

    function getUserTransactions(address _user) public view returns (uint[] memory) {
        return transactionHistory[_user];
    }

    // Add a few transactions for your address, then view them.
}

Check Your Understanding

Consider the following Solidity code snippet:

pragma solidity ^0.8.0;

contract DataStructures {
    mapping(address => uint) public scores;
    uint[] public participants;

    function recordScore(address _player, uint _score) public {
        if (scores[_player] == 0) {
            participants.push(_player);
        }
        scores[_player] = _score;
    }

    function getParticipantCount() public view returns (uint) {
        return participants.length;
    }
}

If recordScore(0xabc..., 100) is called, then recordScore(0xdef..., 200), and finally recordScore(0xabc..., 150), what will getParticipantCount() return?

Recap: Mappings & Dynamic Arrays

You've learned about two essential data structures in Solidity:

  • Mappings: Efficient key-value stores, great for associating data with unique identifiers like addresses. They return default values for unset keys.
  • Dynamic Arrays: Flexible lists that can grow or shrink in size using push() and pop(), ideal when the number of items isn't fixed.

Mastering these will significantly enhance your ability to design robust and scalable smart contracts!

Często zadawane pytania

Czy lekcja „Mapowania i tablice dynamiczne” jest bezpłatna?

Tak — pełny tekst „Mapowania i tablice dynamiczne” jest dostępny za darmo tutaj w sieci. Aby ćwiczyć ją interaktywnie (wbudowany edytor kodu i tutor AI dostępny 24/7) i odblokować resztę kursu Blockchain Smart Contracts with Solidity, przejdź na CoddyKit PRO. Kurs Blockchain Smart Contracts with Solidity zawiera 4 lekcji w sumie.

Co nauczysz się w „Mapowania i tablice dynamiczne”?

Implementuj złożone struktury danych, takie jak mapowania dla par klucz–wartość i tablice dynamiczne dla elastycznych list danych. Ćwiczysz Blockchain Smart Contracts with Solidity z praktycznym kodem, który uruchamiasz bezpośrednio w przeglądarce, a tutor AI dostępny 24/7 odpowiada na Twoje pytania podczas pracy nad lekcją.

Czy potrzebuję doświadczenia, aby zacząć Blockchain Smart Contracts with Solidity?

Nie wymagamy żadnego doświadczenia. Blockchain Smart Contracts with Solidity w CoddyKit jest strukturyzowany dla początkujących i zaawansowanych użytkowników, więc możesz zacząć tutaj lub od początku i uczyć się w swoim tempie. To lekcja 2 z 4.

Ile czasu zajmuje lekcja „Mapowania i tablice dynamiczne”?

Większość lekcji CoddyKit trwa około 5–10 minut. Każda lekcja to mały, interaktywny krok, dzięki czemu robisz systematyczne postępy i zawsze wracasz dokładnie do tego samego miejsca — na webie i w aplikacji.

Czy mogę pisać i uruchamiać kod w tej lekcji Blockchain Smart Contracts with Solidity?

Tak. Każda lekcja Blockchain Smart Contracts with Solidity zawiera wbudowany edytor kodu, więc piszesz i uruchamiasz prawdziwy kod bezpośrednio w przeglądarce i od razu otrzymujesz sprzężenie zwrotne od AI — bez konfiguracji na komputerze.

Wszystkie lekcje w tym kursie

  1. Zmienne stanu i układ pamięci
  2. Mapowania i tablice dynamiczne
  3. Zdarzenia i logowanie danych
  4. Sloty storage i optymalizacja gasu
← Powrót do Blockchain Smart Contracts with Solidity