Small knowledge, big challenge! This article is participating in the creation activity of “Essential Tips for Programmers”.

The interface type

An interface type concretely describes a collection of methods, and a concrete type that implements those methods is an instance of the interface type.

The IO.Writer type is one of the most widely used interfaces because it provides all types of bytes writing abstractions, including file types, memory buffers, network links, HTTP clients, compression tools, hashes, and so on. The IO package defines many other useful interface types. Reader can represent any type of bytes that can be read, and Closer can be any value that can be closed, such as a file or a web link.

package io
type Reader interface {
    Read(p []byte) (n int, err error)
}
type Closer interface {
    Close() error
}
Copy the code

Some new interface types are defined by combining existing interfaces

type ReadWriter interface {
    Reader    Writer
}
type ReadWriteCloser interface {
    Reader    Writer    Closer
}
Copy the code

In this way, we can name an interface with a shorthand without declaring all its methods. This approach is called interface embedding.

Although slightly less concise, we can declare the IO.ReadWriter interface without embedding it as follows

type ReadWriter interface {
    Read(p []byte) (n int, err error)
    Write(p []byte) (n int, err error)
}
Copy the code

The interface conditions

A type implements an interface if it has all the methods that an interface needs.

For example, the *os.File type implements the IO.Reader, Writer, Closer, and ReadWriter interfaces.

The rules for interface specification are very simple: express that a type belongs to an interface as long as the type implements the interface. So:

var w io.Writer
w = os.Stdout           // OK: *os.File has Write method
w = new(bytes.Buffer)   // OK: *bytes.Buffer has Write method
w = time.Second         // compile error: time.Duration lacks Write method
Copy the code

Each group of a concrete type can be represented as an interface type based on their identical behavior. Unlike class-based languages, where a set of interfaces implemented by a class needs to be explicitly defined, in Go we can define new abstractions or groups of specific characteristics as needed without changing the definition of specific types.

– END –

Author: The road to architecture Improvement, ten years of research and development road, Dachang architect, CSDN blog expert, focus on architecture technology precipitation learning and sharing, career and cognitive upgrade, adhere to share practical articles, looking forward to growing with you. Attention and private message I reply “01”, send you a programmer growth advanced gift package, welcome to hook up.

Thanks for reading!