抱歉,您的浏览器无法访问本站
本页面需要浏览器支持(启用)JavaScript
了解详情 >

1.语法

1
using A for * // 效果是,库A中的函数被附着在做任意的类型上

指令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 Test1Test 合约都具有Math合约的功能。

Test1(_test).add(a, b):从库合约可以知道,add函数的形参为 add(Test1 test1, uint256 a, uint256 b),在该函数会默认把调用者作为第一个参数,即 Test1合约。

3. 测试

3.1 部署 Test1, Calculator

image-20230709001543823

3.2 使用Test1的地址调用add函数

image-20230709001656348

成功调用

评论



政策 · 统计 | 本站使用 Volantis 主题设计