What is an interface? Interfaces are abstractions, collections of unimplemented methods that help us decouple by hiding the implementation.

This article will talk about the Go interface.

Implicit interface

To define an interface in Go, you need to use the interface keyword and can only define methods, not member variables, for example:

type error interface {
    Error() string
}
Copy the code

We can implement the Error interface indirectly, without explicitly implementing the interface, by implementing the Error() string method:

type RPCError struct {
    Code    int64
    Message string
}

func (e *RPCError) Error(a) string {
    return fmt.Sprintf("%s, code=%d", e.Message, e.Code)
}
Copy the code

Structure and pointer

We can use structs or Pointers as receivers of interface implementations, but the two types are not the same, and both implementations cannot exist together.

type Cat struct {}
type Duck interface{... }func (c Cat) Quack {}  // Implement the interface using a structure
func (c *Cat) Quack {}  // Use the structure pointer to implement the interface

var d Duck = Cat{}      // Initialize variables with a struct
var d Duck = &Cat{}     // Initialize variables with structure Pointers
Copy the code

This is where the interface to the structure pointer implementation occurs, and compilation cannot pass when using the structure to initialize variables.

Pointer types

There are two different types of interfaces in Go

  • runtime.ifaceRepresents an interface with a set of methods
  • runtime.efaceInterface {}

Note that the interface{} type does not represent any type.