solidity -> delete

  • arrom
  • 更新于 2022-11-11 19:27
  • 阅读 1495

solidity -> delete

delete

  • delete操作符可以用于任何变量(map除外),将其设置成默认值
  • 如果对动态数组使用delete,则删除所有元素,其长度变为0
  • 如果对静态数组使用delete,则重置所有索引的值,数组长度不变
  • 如果对map类型使用delete,什么都不会发生
  • 如果对map类型中的一个键使用delete,则会删除与该键相关的值
// SPDX-License-Identifier: SEE LICENSE IN LICENSE
pragma solidity ^0.8.9;

contract Delete {
    // 01. string
    string public str1 = "hello";

    function deleteStr() public {
        delete str1;
    }

    function setStr(string memory input) public {
        str1 = input;
    }

    // 02. array 对于固定长度的数组,会删除每个元素的值,但是数组长度不变
    uint256[10] public array1 = [1, 2, 3, 4, 5];

    function deleteFiexedArray() public {
        delete array1;
    }

    //03. array new
    uint256[] array2;

    function setArray2() public {
        array2 = new uint256[](10);
        for (uint256 i = 0; i < array2.length; i++) {
            array2[i] = i;
        }
    }

    function getArray2() public view returns (uint256[] memory) {
        return array2;
    }

    function deleteArray2() public {
        delete array2;
    }

    //04. mapping
    mapping(uint256 => string) public m1;

    function setMap() public {
        m1[0] = "hello";
        m1[1] = "solidity";
    }

    //Mapping不允许直接使用delete,但是可以对mapping的元素进行指定删除
    function deleteMapping(uint256 i) public {
        delete m1[i];
    }
}
点赞 1
收藏 0
分享
本文参与登链社区写作激励计划 ,好文好收益,欢迎正在阅读的你也加入。

0 条评论

请先 登录 后评论
arrom
arrom
江湖只有他的大名,没有他的介绍。