3分钟Solidity: 3.5 结构体

32 阅读1分钟

如需获取本内容的最新版本,请参见 Cyfrin.io 上的Structs(代码示例)

您可以通过创建结构体来定义自己的类型。 它们对于将相关数据分组在一起非常有用。 结构体可以在合约外部声明,并在另一个合约中导入。

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

contract Todos {
    struct Todo {
        string text;
        bool completed;
    }

    // An array of 'Todo' structs
    Todo[] public todos;

    function create(string calldata _text) public {
        // 3 ways to initialize a struct
        // - calling it like a function
        todos.push(Todo(_text, false));

        // key value mapping
        todos.push(Todo({text: _text, completed: false}));

        // initialize an empty struct and then update it
        Todo memory todo;
        todo.text = _text;
        // todo.completed initialized to false

        todos.push(todo);
    }

    // Solidity automatically creates a getter for 'todos' so
    // you don't actually need this function.
    function get(uint256 _index)
        public
        view
        returns (string memory text, bool completed)
    {
        Todo storage todo = todos[_index];
        return (todo.text, todo.completed);
    }

    // update text
    function updateText(uint256 _index, string calldata _text) public {
        Todo storage todo = todos[_index];
        todo.text = _text;
    }

    // update completed
    function toggleCompleted(uint256 _index) public {
        Todo storage todo = todos[_index];
        todo.completed = !todo.completed;
    }
}

Remix Lite 尝试一下

solidity-结构体

声明并导入结构体

声明了结构体的文件

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.26;
// 保存为 'StructDeclaration.sol'

struct Todo {
    string text;
    bool completed;
}

Remix Lite 尝试一下

solidity-结构体声明

导入上述结构体的文件

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

import "./StructDeclaration.sol";

contract Todos {
    // 一个包含 'Todo' 结构体的数组
    Todo[] public todos;
}

Remix Lite 尝试一下

solidity-struct


END