Solidity interface 接口

接口本意是物体之间连接的部位。例如:电脑的 usb 接口可以用来连接鼠标也可以连接U盘和硬盘。因此,使用标准的接口可以极大的拓展程序的功能。在 solidity 语言中,接口可以用来接受相同规则的合约,实现可更新的智能合约。

interface 类似于抽象合约,但它们不能实现任何功能。还有其他限制:

  • 无法继承其他合约或接口。
  • 所有声明的函数必须是 external 的。
  • 无法定义构造函数。
  • 无法定义变量。
  • 无法定义结构。

1. 接口定义

接口需要有interface关键字,并且内部只需要有函数的声明,不用实现。

只要某合约中有和词接口相同的函数声明,就可以被此合约所接受。

interface 接口名{
    函数声明;
}

例子:

interface animalEat{
      function eat() public returns(string);
}

 

2. 接口使用

在下面的例子中,定义了cat合约以及dog合约。他们都有eat方法.以此他们都可以被上面的animalEat接口所接收。

 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 方法。