Home Backend Development Golang What is the relationship between types and interfaces in Go language

What is the relationship between types and interfaces in Go language

Jan 06, 2023 pm 07:52 PM
golang interface go language

In the Go language, there is a one-to-many and many-to-one relationship between types and interfaces. A type can implement multiple interfaces at the same time, and the interfaces are independent of each other and do not know each other's implementation. Multiple types can also implement the same interface: the methods of an interface do not necessarily need to be fully implemented by a type. The methods of the interface can be implemented by embedding other types or structures in the type. In other words, users do not care whether the method of an interface is fully implemented through one type, or whether it is implemented through multiple structures embedded in a structure and pieced together.

What is the relationship between types and interfaces in Go language

The operating environment of this tutorial: Windows 7 system, GO version 1.18, Dell G3 computer.

The relationship between Go language types and interfaces

In Go language, there is a one-to-many and many-to-one relationship between types and interfaces. These common concepts will be listed below to facilitate readers to understand the implementation relationship between interfaces and types in complex environments.

A type can implement multiple interfaces

A type can implement multiple interfaces at the same time, and the interfaces are independent of each other and do not know each other's implementation.

Two programs on the network exchange data through a two-way communication connection. One end of the connection is called a Socket. Socket can read and write data at the same time, this feature is similar to a file. Therefore, during development, the reading and writing features of both files and Sockets are abstracted into independent reader and writer concepts.

Sockets, like files, also need to release resources after use.

Use the interface to describe the features of Socket that can write data and need to be closed. Please refer to the following code:

type Socket struct {
}
func (s *Socket) Write(p []byte) (n int, err error) {
    return 0, nil
}
func (s *Socket) Close() error {
    return nil
}
Copy after login

The Write() method of the Socket structure implements the io.Writer interface:

type Writer interface {
    Write(p []byte) (n int, err error)
}
Copy after login

At the same time, the Socket structure also implements the io.Closer interface:

type Closer interface {
    Close() error
}
Copy after login

Using the code of the Writer interface implemented by Socket, there is no need to know whether the implementer of the Writer interface has the characteristics of the Closer interface. Similarly, the code using the Closer interface does not know that the Socket has implemented the Writer interface, as shown in the following figure.

What is the relationship between types and interfaces in Go language
Figure: The use and implementation process of the interface

The Writer interface and Closer interface codes implemented using the Socket structure in the code are as follows:

// 使用io.Writer的代码, 并不知道Socket和io.Closer的存在
func usingWriter( writer io.Writer){
    writer.Write( nil )
}
// 使用io.Closer, 并不知道Socket和io.Writer的存在
func usingCloser( closer io.Closer) {
    closer.Close()
}
func main() {
    // 实例化Socket
    s := new(Socket)
    usingWriter(s)
    usingCloser(s)
}
Copy after login

usingWriter () and usingCloser() are completely independent. They do not know the existence of each other, nor do they know that the interface they use is implemented by Socket.

Multiple types can implement the same interface

The methods of an interface do not necessarily need to be completely implemented by one type. The methods of the interface can be embedded in other types in the type. type or structure. In other words, users do not care whether the method of an interface is fully implemented through one type, or whether it is implemented through multiple structures embedded in a structure and pieced together.

The Service interface defines two methods: one is to start the service (Start()), and the other is to output the log (Log()). Use the GameService structure to implement Service. GameService's own structure can only implement the Start() method, and the Log() method in the Service interface has been implemented by a logger (Logger) that can output logs. There is no need to encapsulate GameService. Or implement it again. Therefore, choosing to embed Logger into GameService can avoid code redundancy and simplify the code structure to the greatest extent. The detailed implementation process is as follows:

// 一个服务需要满足能够开启和写日志的功能
type Service interface {
    Start()  // 开启服务
    Log(string)  // 日志输出
}
// 日志器
type Logger struct {
}
// 实现Service的Log()方法
func (g *Logger) Log(l string) {
}
// 游戏服务
type GameService struct {
    Logger  // 嵌入日志器
}
// 实现Service的Start()方法
func (g *GameService) Start() {
}
Copy after login

The code description is as follows:

  • Line 2 defines the service interface. A service needs to implement the Start() method and the log method.

  • Line 8 defines the logger structure that can output logs.

  • In line 12, add the Log() method to the Logger and implement the Log() method of the Service.

  • Line 17 defines the GameService structure.

  • Line 18, embed the Logger logger in GameService to implement the logging function.

  • Line 22, GameService’s Start() method implements Service’s Start() method.

At this point, instantiate GameService and assign the instance to Service. The code is as follows:

var s Service = new(GameService)
s.Start()
s.Log(“hello”)
Copy after login

s You can use the Start() method and Log() method, Among them, Start() is implemented by GameService, and the Log() method is implemented by Logger.

【Related recommendations: Go video tutorial, Programming teaching

The above is the detailed content of What is the relationship between types and interfaces in Go language. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1664
14
PHP Tutorial
1268
29
C# Tutorial
1242
24
How to solve the user_id type conversion problem when using Redis Stream to implement message queues in Go language? How to solve the user_id type conversion problem when using Redis Stream to implement message queues in Go language? Apr 02, 2025 pm 04:54 PM

The problem of using RedisStream to implement message queues in Go language is using Go language and Redis...

What should I do if the custom structure labels in GoLand are not displayed? What should I do if the custom structure labels in GoLand are not displayed? Apr 02, 2025 pm 05:09 PM

What should I do if the custom structure labels in GoLand are not displayed? When using GoLand for Go language development, many developers will encounter custom structure tags...

What is the difference between an abstract class and an interface in PHP? What is the difference between an abstract class and an interface in PHP? Apr 08, 2025 am 12:08 AM

The main difference between an abstract class and an interface is that an abstract class can contain the implementation of a method, while an interface can only define the signature of a method. 1. Abstract class is defined using abstract keyword, which can contain abstract and concrete methods, suitable for providing default implementations and shared code. 2. The interface is defined using the interface keyword, which only contains method signatures, which is suitable for defining behavioral norms and multiple inheritance.

Which libraries in Go are developed by large companies or provided by well-known open source projects? Which libraries in Go are developed by large companies or provided by well-known open source projects? Apr 02, 2025 pm 04:12 PM

Which libraries in Go are developed by large companies or well-known open source projects? When programming in Go, developers often encounter some common needs, ...

Golang's Purpose: Building Efficient and Scalable Systems Golang's Purpose: Building Efficient and Scalable Systems Apr 09, 2025 pm 05:17 PM

Go language performs well in building efficient and scalable systems. Its advantages include: 1. High performance: compiled into machine code, fast running speed; 2. Concurrent programming: simplify multitasking through goroutines and channels; 3. Simplicity: concise syntax, reducing learning and maintenance costs; 4. Cross-platform: supports cross-platform compilation, easy deployment.

In Go programming, how to correctly manage the connection and release resources between Mysql and Redis? In Go programming, how to correctly manage the connection and release resources between Mysql and Redis? Apr 02, 2025 pm 05:03 PM

Resource management in Go programming: Mysql and Redis connect and release in learning how to correctly manage resources, especially with databases and caches...

How to ensure concurrency is safe and efficient when writing multi-process logs? How to ensure concurrency is safe and efficient when writing multi-process logs? Apr 02, 2025 pm 03:51 PM

Efficiently handle concurrency security issues in multi-process log writing. Multiple processes write the same log file at the same time. How to ensure concurrency is safe and efficient? This is a...

Golang vs. Python: Performance and Scalability Golang vs. Python: Performance and Scalability Apr 19, 2025 am 12:18 AM

Golang is better than Python in terms of performance and scalability. 1) Golang's compilation-type characteristics and efficient concurrency model make it perform well in high concurrency scenarios. 2) Python, as an interpreted language, executes slowly, but can optimize performance through tools such as Cython.

See all articles