solidity[47]-interface
接口本意是物体之间连接的部位。例如电脑的usb接口可以用来连接鼠标也可以连接U盘和硬盘。因此,使用标准的接口可以极大的拓展程序的功能。在solidity语言中,接口可以用来接受相同规则的合约,实现可更新的智能合约。
接口定义接口需要有interface关键字,并且内部只需要有函数的声明,不用实现。
只要某合约中有和词接口相同的函数声明,就可以被此合约所接受。
1
2
3
interface 接口名{
函数声明;
}
例子:
1
2
3
interface animalEat{
function eat() public returns(string);
}
接口使用
在下面的例子中,定义了cat合约以及dog合约。他们都有eat方法.以此他们都可以被上面的animalEat接口所接收。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
contract cat{
string name;
function eat() public returns(string){
return "cat eat fish";
}
function sleep() public returns(string){
return "sleep";
}
}
contract dog{
string name;
function eat() public returns(string){
return "dog miss you";
}
function swim() public returns(string){
return "sleep";
}
}
interface animalEat{
function eat() public returns(string);
}
contract animal{
function test(address _addr) returns(string){
animalEat generalEat = animalEat(_addr);
return generalEat.eat();
}
}
在合约animal中,调用函数test,如果传递的是部署的cat的合约地址,那么我们在调用接口的eat方法时,实则调用了cat合约的eat方法。 同理,如果传递的是部署的dog的合约地址,那么我们在调用接口的eat方法时,实则调用了dog合约的eat方法。
本文链接:https://dreamerjonson.com/2018/11/23/solidity-47-interface/
版权声明:本博客所有文章除特别声明外,均采用CC BY 4.0 CN协议许可协议。转载请注明出处!
声明:本站所有文章资源内容,如无特殊说明或标注,均为采集网络资源。如若本站内容侵犯了原著者的合法权益,可联系本站删除。