Função

# Função

Existem diversas formas de retornar saídas de uma função.

Funções públicas não podem aceitar certos tipos de dados como entradas e saídas

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;

contract Funcao {
    // Funções podem retornar valores múltiplos.
    function returnMany()
        public
        pure
        returns (
            uint,
            bool,
            uint
        )
    {
        return (1, true, 2);
    }

    // Valores retornados podem ser nomeados.
    function named()
        public
        pure
        returns (
            uint x,
            bool b,
            uint y
        )
    {
        return (1, true, 2);
    }

    // Valores de retorno podem ser atribuídos a seus nomes.
    // Nesse caso, a instrução de retorno pode ser omitida.
    function assigned()
        public
        pure
        returns (
            uint x,
            bool b,
            uint y
        )
    {
        x = 1;
        b = true;
        y = 2;
    }

    // Usa atribuição de desestruturação ao chamar outro
    // função que retorna múltiplos valores.
    function destructingAssigments()
        public
        pure
        returns (
            uint,
            bool,
            uint,
            uint,
            uint
        )
    {
        (uint i, bool b, uint j) = returnMany();

        // Valores podem ser deixados de fora.
        (uint x, , uint y) = (4, 5, 6);

        return (i, b, j, x, y);
    }

    // Não pode usar mapa nem para entrada nem para saída

    // Pode usar array para entrada
    function arrayInput(uint[] memory _arr) public {}

    // Pode usar array para saída
    uint[] public arr;

    function arrayOutput() public view returns (uint[] memory) {
        return arr;
    }
}

// Função de chamada com entradas de chave-valor
contract XYZ {
    function someFuncWithManyInputs(
        uint x,
        uint y,
        uint z,
        address a,
        bool b,
        string memory c
    ) public pure returns (uint) {}

    function callFunc() external pure returns (uint) {
        return someFuncWithManyInputs(1, 2, 3, address(0), true, "c");
    }

    function callFuncWithKeyValue() external pure returns (uint) {
        return
            someFuncWithManyInputs({a: address(0), b: true, c: "c", x: 1, y: 2, z: 3});
    }
}

# Teste no Remix

Last Updated: 22/01/2024 22:26:13