ethereum - 删除数组中的元素,但结构仍在内部
问题描述
我有这个结构数组
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--
但在我必须解决这个问题之前
解决方案
试试这个代码
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; }
}
推荐阅读
- java - 在 Java 中验证 HTML 片段?
- python - 在openCV中没有从网络摄像头获得连续的视频输出
- google-apps-script - 使用自定义字段创建联系人
- python - 我的 django 没用(我正在学习教程)
- xcode - LLDB 在 expr 函数时在断点处停止
- python - 使用 Pandas 中的函数替换列中的 NaN 时面临索引越界错误
- mysql - 使用 group by 从 mysql 获取最后的数据
- c# - 如何在 Rebex 中连接 privateKey 和证书
- javascript - 跟随光标元素
- sql - CASE 语句返回多条记录