首页 > 解决方案 > 删除数组中的元素,但结构仍在内部

问题描述

我有这个结构数组

struct Prodotto {
    string titolo;
    address owner_address;
}

Prodotto[] public prodotti;

我创建了两个这样的产品:

titolo: titolo stravolto
owner: 0x144c9617C69B52547f7c2c526352E137488FAF0c

titolo: titolo secondo prodotto
owner: 0xa53709839ab6Da3ad9c1518Ed39a4a0fFCbA3684

我想删除索引为 0 的元素

在我的合同中我有这个功能

function deleteProdotto(uint _id_prodotto) external payable onlyOwnerOf(_id_prodotto) {
  delete prodotti[0];    
}

如果我将元素检索到索引 0,我就有这样的产品

titolo:
owner: 0x0000000000000000000000000000000000000000

如何删除该索引?我知道在那之后我必须做

prodotti.length--

但在我必须解决这个问题之前

标签: ethereumsoliditysmartcontracts

解决方案


试试这个代码

contract test {
    struct Prodotto {
        string titolo;
        address owner_address;
    }
    Prodotto[] public prodotti;

    constructor() public {
        for (uint i = 0; i < 5; i++) {
            prodotti.push(Prodotto({
                titolo: 'one more',
                owner_address: address(i)
            }));
        }
    }

    function remove(uint index) public {
        for (uint i = index; i < prodotti.length-1; i++) {
            prodotti[i] = prodotti[i+1];
        }
        delete prodotti[prodotti.length-1];
        prodotti.length--;
    }

    function check() public view returns(uint256) { return prodotti.length; }
}

推荐阅读