Skip to content

Latest commit

 

History

History
40 lines (30 loc) · 1.47 KB

File metadata and controls

40 lines (30 loc) · 1.47 KB

库合约

库合约是一种特殊的合约,为了提升Solidity代码的复用性和减少gas而存在。

使用库合约两种方式:

  1. 利用using for指令
  2. 通过库合约名称调用函数
// 以使用Strings库合约为例:
contract Helloworld {
    using Strings for uint;

    // 两种调用库合约方式
    // 方式一(常用)
    function hello(uint _num) external pure  returns (string memory) {
        return _num.toString();
    }

    // 方式二
    function hello2(uint _num) external pure  returns (string memory) {
        return Strings.toString(_num);
    }
}

库合约与普通合约的区别

  • 不能存在状态变量
  • 不能够继承或被继承
  • 不能接收以太币
  • 不可以被销毁

常用的库合约有:

  • Strings:将uint256转换为String
  • Address:判断某个地址是否为合约地址
  • Create2:更安全的使用Create2 EVM opcode
  • Arrays:跟数组相关的库合约