Let's talk about Go's interface | Go theme month

What is an interface? An interface is an abstraction, a collection of unimplemented methods, which can help us hide the specific implementation and achieve decoupling.

This article will talk about Go interface related content.

implicit interface

Defining an interface in the Go language requires the use of the interface keyword, and can only define methods, not member variables, for example:

type error interface {
    Error() string
}
复制代码

We can implement the interface indirectly by implementing the Error() stringmethod errorwithout explicitly implementing the interface:

type RPCError struct {
    Code    int64
    Message string
}

func (e *RPCError) Error() string {
    return fmt.Sprintf("%s, code=%d", e.Message, e.Code)
}
复制代码

structs and pointers

We can use structs or pointers as receivers of interface implementations, but these two types are not the same, and both implementations cannot exist at the same time.

type Cat struct {}
type Duck interface { ... }

func (c  Cat) Quack {}  // 使用结构体实现接口
func (c *Cat) Quack {}  // 使用结构体指针实现接口

var d Duck = Cat{}      // 使用结构体初始化变量
var d Duck = &Cat{}     // 使用结构体指针初始化变量
复制代码

Here, the interface implemented by the structure pointer occurs. When the structure is used to initialize the variable, the compilation cannot pass.

pointer type

There are two different types of interfaces in Go

  • runtime.ifaceRepresents an interface with a set of methods
  • runtime.efaceRepresents an interface interface{} that does not contain any methods

Note that interface{}types do not represent arbitrary types.

Guess you like

Origin juejin.im/post/6945476531439271972