0Pricing
Web3 & DApp Development Fundamentals · Урок

Ссылочные типы

Массивы, структуры и отображения

«Ссылочные типы» — бесплатный урок Web3 & DApp Development Fundamentals на CoddyKit. Это урок 2 из 4. Ты можешь прочитать весь урок бесплатно ниже — а потом практиковать его прямо в браузере с встроенным редактором кода и ИИ-репетитором 24/7. Это часть пути обучения Web3 & DApp Development Fundamentals, и твой прогресс синхронизируется между веб-версией и приложением CoddyKit. Курс Web3 & DApp Development Fundamentals содержит 4 уроков всего.

Части этого урока еще не переведены и отображаются на английском.

What Are Reference Types?

Reference types describe data that is too large to fit in one slot, so variables refer to a location rather than holding the data directly.

The three reference types are arrays, structs, and mappings. When you use them you must think about their data location: storage, memory, or calldata.

Fixed-Size Arrays

A fixed-size array has a length set at compile time and cannot grow. The type uint[3] always holds exactly three values.

Use .length to read the size. Out-of-bounds access reverts.

<code>uint[3] public scores = [10, 20, 30];

function first() public view returns (uint) {
    return scores[0];
}</code>

Dynamic Arrays

A dynamic array can grow and shrink. Declare it as uint[]. In storage you can push to append and pop to remove the last element.

<code>uint[] public nums;

function add(uint n) public {
    nums.push(n);
}

function removeLast() public {
    nums.pop();
}</code>

Bytes and String

bytes is a dynamically-sized byte array and string is its UTF-8 text cousin. Both are reference types.

Note: string has no .length or indexing; convert to bytes first to inspect raw bytes.

<code>string public name = 'Alice';

function nameLength() public view returns (uint) {
    return bytes(name).length;
}</code>

Defining Structs

A struct groups related variables into one custom type. It is ideal for modeling entities like users, orders, or tokens.

<code>struct User {
    string name;
    uint256 balance;
    bool active;
}</code>

Using Structs

You can create a struct with positional or named arguments and store it. Reading a struct from storage gives you a reference you can modify.

<code>User public owner;

function setup(string memory n) public {
    owner = User({ name: n, balance: 0, active: true });
}</code>

Mappings

A mapping is a key-value store, like a hash table. It is one of the most used structures in smart contracts, for example tracking balances per address.

Keys are not stored, so you cannot iterate a mapping or get its length.

<code>mapping(address => uint256) public balances;

function deposit() public payable {
    balances[msg.sender] += msg.value;
}</code>

Nested Mappings

Mappings can be nested to model relationships, such as allowances where one owner permits multiple spenders.

This pattern is the heart of the ERC-20 allowance system.

<code>mapping(address => mapping(address => uint256)) public allowance;

function approve(address spender, uint256 amount) public {
    allowance[msg.sender][spender] = amount;
}</code>

Combining Structs and Mappings

A powerful pattern is mapping keys to structs. This lets you store rich records keyed by an id or address.

<code>struct Order {
    uint256 amount;
    bool paid;
}

mapping(uint256 => Order) public orders;

function createOrder(uint256 id, uint256 amt) public {
    orders[id] = Order({ amount: amt, paid: false });
}</code>

Arrays of Structs

You can keep a dynamic array of structs when you need ordered, iterable records. Combine it with a mapping for fast lookup.

<code>struct Item { string name; uint256 price; }
Item[] public items;

function addItem(string memory n, uint256 p) public {
    items.push(Item(n, p));
}</code>

Reference Semantics

When you assign a storage reference type to a local storage variable, both point to the same data. Changes through one are visible through the other.

A memory copy, in contrast, is independent.

<code>uint[] public data;

function tweak() public {
    uint[] storage ref = data; // alias
    ref.push(42);              // also changes data
}</code>

Quick Check

Test your understanding of reference types.

Recap

You explored Solidity reference types:

  • Arrays (fixed and dynamic), plus bytes and string
  • Structs to group related fields
  • Mappings and nested mappings for key-value storage
  • Powerful combinations like mapping-to-struct and arrays-of-structs

Reference types share locations, so always be deliberate about storage versus memory.

Часто задаваемые вопросы

Урок «Ссылочные типы» бесплатный?

Да — полный текст урока «Ссылочные типы» бесплатно доступен здесь в веб-версии. Чтобы практиковать его интерактивно (встроенный редактор кода и ИИ-репетитор 24/7) и разблокировать остальной курс Web3 & DApp Development Fundamentals, подпишись на CoddyKit PRO. Курс Web3 & DApp Development Fundamentals содержит 4 уроков всего.

Чему я научусь в уроке «Ссылочные типы»?

Массивы, структуры и отображения Ты практикуешь Web3 & DApp Development Fundamentals с помощью реального кода, который запускаешь прямо в браузере, и ИИ-репетитор 24/7 отвечает на твои вопросы во время урока.

Нужен ли мне опыт, чтобы начать Web3 & DApp Development Fundamentals?

Предыдущий опыт не требуется. Web3 & DApp Development Fundamentals на CoddyKit структурирован для всех уровней — от новичков до продвинутых, поэтому ты можешь начать отсюда или с самого начала и учиться в своем темпе. Это урок 2 из 4.

Сколько времени занимает урок «Ссылочные типы»?

Большинство уроков CoddyKit занимают около 5–10 минут. Каждый из них компактный и интерактивный, поэтому ты постоянно делаешь прогресс и продолжаешь с того же места в веб-версии и приложении.

Можно ли писать и запускать код в этом уроке Web3 & DApp Development Fundamentals?

Да. Каждый урок Web3 & DApp Development Fundamentals включает встроенный редактор кода, поэтому ты пишешь и запускаешь реальный код прямо в браузере и получаешь моментальную обратную связь от AI — локальная установка не требуется.

Все уроки этого курса

  1. Типы значений
  2. Ссылочные типы
  3. Хранилище и память
  4. Константы и неизменяемые значения
← Назад к Web3 & DApp Development Fundamentals