Structs

# Structs

Você pode definir seu próprio tipo de dado criando um struct.

Elas são úteis para agrupar dados do mesmo tipo.

Os structs podem ser declarados fora de um contrato e importados em outro contrato.

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

contract Afazeres {
    struct Afazer {
        string texto;
        bool concluida;
    }

    // Uma array de 'Afazer' structs
    Afazer[] public afazeres;

    function create(string calldata _text) public {
        // 3 maneiras de inicializar uma struct

        // 1. Chamando como uma função
        afazeres.push(Afazer(_text, false));

        // 2. Mapping de chave-valor
        afazeres.push(Afazer({texto: _text, concluida: false}));

        // 3. Inicialize uma estrutura vazia e, em seguida, atualize-a
        Afazer memory afazer;
        afazer.texto = _text;

        // afazer.concluida é inicializado como false
        afazeres.push(afazer);
    }

    // Solidity automaticamente criou um getter para 'afazeres' então
    // você não precisa realmente dessa função.
    function get(uint _index) public view returns (string memory texto, bool concluida) {
        Afazer storage afazer = afazeres[_index];
        return (afazer.texto, afazer.concluida);
    }

    // atualizar texto
    function update(uint _index, string calldata _text) public {
        Afazer storage afazer = afazeres[_index];
        afazer.texto = _text;
    }

    // atualização concluída
    function toggleCompleted(uint _index) public {
        Afazer storage afazer = afazeres[_index];
        afazer.concluida = !afazer.concluida;
    }
}

# Declarando e Importando Struct

Arquivo no qual a struct é declarada

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

struct Afazer {
    string texto;
    bool concluida;
}

Arquivo que importa a struct acima

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

import "./StructDeclaration.sol";

contract Afazeres {
    // Um array de structs 'Afazer'
    Afazer[] public afazeres;
}
Last Updated: 22/01/2024 22:26:13