工具类合约或库的使用
方法一

把工具功能写成合约,如下:

1
2
3
4
5
6
7
8
9
10
contract Console {
event LogUint(string, uint);
function log(string s , uint x) internal {
emit LogUint(s, x);
}
event LogInt(string, int);
function log(string s , int x) internal {
emit LogInt(s, x);
}
}

引用时,import “./Console.sol”

contract myContract is Console{

log(“timeNow”,now);

}

方法二

把工具功能写成库library,如下

1
2
3
4
5
6
7
8
9
10
library Console {
event LogUint(string, uint);
function log(string s , uint x) internal {
emit LogUint(s, x);
}
event LogInt(string, int);
function log(string s , int x) internal {
emit LogInt(s, x);
}
}

==注意==

在library中我们不能定义任何storage类型的变量。因为library只是意味着代码的重用而不是进行state的状态管理。使用前再查询确认下。


引用时,import {Console} from “./Console.sol”

contract myContract {

​ Console.log(“timeNew”,now);

}

访问library中的数据或方法时,使用点,libraryName.xxx来访问。

Author: superman285
Link: https://skr.dog/2019/02/22/工具类合约或库的使用/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.