[Solidity] How to add element to the array?

This section explains how to add element to the array in Solidity.

Syntax

To add element to an array in Solidity, use the push method.

Note that the added element is inserted at the end of the array.

array.push(value);

Sample Code

// SPDX-License-Identifier: GPL-3.0

pragma solidity >=0.7.0 <0.9.0;

contract Test {
    uint[] public numbers;

    function addNumber(uint num) public {
        // Add an element to the array
        numbers.push(num);
    }

    function getNumbers() public view returns(uint[] memory) {
        return numbers;
    }
}

Previously, array.push would return the length of the newly created array as the return value, but the specification has been changed since the Solidity 0.6.0 version to not return a return value.

タイトルとURLをコピーしました