Solidity-Learning

Solidity 学习笔记

View the Project on GitHub XdpCs/Solidity-Learning

011-结构体(Struct)

背景

通过学习Solidity,然后输出文章检验自己的学习成果Github仓库

欢迎大家关注我的X

基础知识

例子

例子

该例子是通过使用结构体(Struct)存储待办事项的例子

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

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

    Todo[] public todos;

    function createOneWay(string memory _text) public {
        todos.push(Todo(_text, false));
    }

    function createTwoWay(string memory _text) public {
        todos.push(Todo({text : _text, completed : false}));
    }

    function createThreeWay(string memory _text) public {
        Todo memory todo;
        todo.text = _text;
        todos.push(todo);
    }

    function get(uint _index) public view returns (string memory text, bool completed){
        Todo storage todo = todos[_index];
        return (todo.text, todo.completed);
    }

    function update(uint _index, string memory _text) public {
        Todo storage todo = todos[_index];
        todo.text = _text;
    }

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

程序解析

struct Todo {
    string text;
    bool completed;
}
Todo[] public todos;
function createOneWay(string memory _text) public {
    todos.push(Todo(_text, false));
}

function createTwoWay(string memory _text) public {
    todos.push(Todo({text : _text, completed : false}));
}

function createThreeWay(string memory _text) public {
    Todo memory todo;
    todo.text = _text;
    todos.push(todo);
}
function get(uint _index) public view returns (string memory text, bool completed){
    Todo storage todo = todos[_index];
    return (todo.text, todo.completed);
}
function update(uint _index, string memory _text) public {
    Todo storage todo = todos[_index];
    todo.text = _text;
}
function toggleCompleted(uint _index) public {
    Todo storage todo = todos[_index];
    todo.completed = !todo.completed;
}

链接