3分钟Solidity: 6.3 library库

23 阅读1分钟

欢迎订阅专栏3分钟Solidity--智能合约--Web3区块链技术必学

如需获取本内容的最新版本,请参见 Cyfrin.io 上的Library(代码示例)

库类似于合约,但不能声明任何状态变量,也不能发送以太币。

如果所有库函数都是内部的,则库会被嵌入到合约中。

否则,必须在部署合约之前先部署库并进行链接。

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

library Math {
    function sqrt(uint256 y) internal pure returns (uint256 z) {
        if (y > 3) {
            z = y;
            uint256 x = y / 2 + 1;
            while (x < z) {
                z = x;
                x = (y / x + x) / 2;
            }
        } else if (y != 0) {
            z = 1;
        }
        // else z = 0 (default value)
    }
}

contract TestMath {
    function testSquareRoot(uint256 x) public pure returns (uint256) {
        return Math.sqrt(x);
    }
}

// 数组函数,用于删除指定索引处的元素并重新组织数组,确保元素之间没有空隙。
library Array {
    function remove(uint256[] storage arr, uint256 index) public {
        // 将最后一个元素移动到要删除的位置
        require(arr.length > 0, "无法从空数组中移除");
        arr[index] = arr[arr.length - 1];
        arr.pop();
    }
}

contract TestArray {
    using Array for uint256[];

    uint256[] public arr;

    function testArrayRemove() public {
        for (uint256 i = 0; i < 3; i++) {
            arr.push(i);
        }

        arr.remove(1);

        assert(arr.length == 2);
        assert(arr[0] == 0);
        assert(arr[1] == 2);
    }
}

Remix Lite 尝试一下

solidity-library


END