指令using A for B;用来附着库里定义的函数(从库A)到任意类型B。这些函数将会默认接收调用函数对象的实例作为第一个参数。
2. 示例代码
2.1 Math库合约:
1 2 3 4 5 6 7 8 9 10 11 12
// 声明一个库合约 library Math { // 定义一个加法函数 function add(Test1 test1, uint256 a, uint256 b) external pure returns (uint256) { return a + b; } // 定义一个乘法函数 function mul(uint256 a, uint256 b) external pure returns (uint256) { return a * b; } }
2.2 测试合约:
1 2 3 4 5 6 7 8
// 测试合约 contract Test1 { address owner;
function getOwner() external view returns(address) { return owner; } }
2.3 引用库合约:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
// 合约中使用库合约 contract Calculator{
using Math for Test1;
// 使用库合约中的加法函数 function add(address _test, uint256 a, uint256 b) external pure returns (uint256) { return Test1(_test).add(a, b); } // 使用库合约中的乘法函数 function mul(uint256 a, uint256 b) external pure returns (uint256) { return Math.mul(a, b); } }
2.4 解读引用库合约
using Math for Test1:Test 合约都具有Math合约的功能。
Test1(_test).add(a, b):从库合约可以知道,add函数的形参为 add(Test1 test1, uint256 a, uint256 b),在该函数会默认把调用者作为第一个参数,即 Test1合约。