阅读(1647) (0)

接口

2022-05-13 11:29:27 更新

接口类似于抽象合约,但它们不能实现任何功能。还有更多限制:

  • 它们不能从其他合约继承,但可以从其他接口继承。
  • 所有声明的函数在接口中必须是外部的,即使它们在合约中是公共的。
  • 他们不能声明构造函数。
  • 他们不能声明状态变量。
  • 他们不能声明修饰符。

未来可能会取消其中一些限制。

接口基本上仅限于 Contract ABI 可以表示的内容,ABI 和接口之间的转换应该是可能的,不会有任何信息丢失。

接口由它们自己的关键字表示:

// SPDX-License-Identifier: GPL-3.0
pragma solidity >=0.6.2 <0.9.0;

interface Token {
    enum TokenType { Fungible, NonFungible }
    struct Coin { string obverse; string reverse; }
    function transfer(address recipient, uint amount) external;
}

合约可以像继承其他合约一样继承接口。

接口中声明的所有函数都是隐式声明的virtual,任何覆盖它们的函数都不需要override关键字。这并不自动意味着一个覆盖函数可以再次被覆盖——这只有在覆盖函数被标记的情况下才有可能virtual。

接口可以从其他接口继承。这与普通继承具有相同的规则。

// SPDX-License-Identifier: GPL-3.0
pragma solidity >=0.6.2 <0.9.0;

interface ParentA {
    function test() external returns (uint256);
}

interface ParentB {
    function test() external returns (uint256);
}

interface SubInterface is ParentA, ParentB {
    // Must redefine test in order to assert that the parent
    // meanings are compatible.
    function test() external override(ParentA, ParentB) returns (uint256);
}

在接口和其他类似合约的结构中定义的类型可以从其他合约访问:Token.TokenType或Token.Coin.