向 Solidity 结构添加更新和删除功能

Add update and delete functions to Solidity struct

我正在尝试向我的结构添加一个更新函数和一个删除函数,但是它不起作用。

有人知道如何使用这些功能吗?

pragma solidity 0.7.5;

contract dogs{

    struct Person{
        uint age;
        string name;
    }
    Person[]people;
    function addNewPerson(uint _age, string memory _name)public {
        Person memory newPerson = Person(_age, _name);
        people.push(newPerson);

    }
    function getPerson(uint _index)public view returns(uint, string memory){
        Person memory personToReturn = people[_index];
        return(personToReturn.age, personToReturn.name);
    }
// to replace and old person with a knew person

    function update(uint _index) public view returns(uint, string memory){
        Person memory updatePerson = people[_index];
    return(updatePerson.age, updatePerson.name);
    }
// delete button for indexs

    function destory(uint _index)public{
        delete people[_index];

    }
}

在下面尝试智能合约,我还插入了一些评论以了解您在合约中的错误之处:

// SPDX-License-Identifier: MIT
pragma solidity 0.7.5;

contract Dogs {

    struct Person{
        uint age;
        string name;
    }

    Person[] people;

    function addNewPerson(uint _age, string memory _name)public {
        Person memory newPerson = Person(_age, _name);
        people.push(newPerson);
    }

    function getPerson(uint _index)public view returns(uint, string memory){
        Person memory personToReturn = people[_index];
        return(personToReturn.age, personToReturn.name);
    }

    // to replace and old person with a knew person
    function update(uint _index, uint _newAge, string memory _newName) public returns(uint, string memory) {
        Person memory updatePerson = people[_index];
        updatePerson.age = _newAge;
        updatePerson.name = _newName;
        // You can replace the old person at specific index to a new person.
        // You can do it, using the statement declared below this line  
        people[_index] = updatePerson;
        return(updatePerson.age, updatePerson.name);
    }
    
    // delete button for indexs
    function destory(uint _index) public {
        delete people[_index];
    }
}

如果您在执行 delete 函数时收到 out of gas 错误,请记住提高气体限制。 关注addNewPerson函数,有效。