Home Backend Development Golang How are interfaces defined and implemented in Go language?

How are interfaces defined and implemented in Go language?

Jun 10, 2023 pm 04:46 PM
interface go language accomplish

How are interfaces defined and implemented in Go language?

Go language is a modern programming language. It is designed to be simple and easy to understand, and it is also efficient, fast and reliable. In Go language, interface is a very important concept. Through interfaces, we can define a collection of methods and then let other types implement these methods. In this article, we will explore in depth the definition and implementation of interfaces in the Go language.

1. Definition of interface

In Go, an interface is a collection of methods. Specifically, the interface contains several methods, each of which must have a fixed signature. These methods can be empty methods, or they can have some specific implementation codes. The set of methods defined through the interface is associated with the specific type implementation and can be used to implement polymorphism.

The way to define an interface is very simple. You only need to use the following syntax:

type 接口名 interface {
    方法1(参数列表) 返回值列表
    方法2(参数列表) 返回值列表
    ...
}
Copy after login

Among them, the interface name is the name we specify for the interface. Method 1, method 2, etc. are all the names of the interface. Contains methods.

For example, we define an interface Manager, which contains two methods: Add and Remove. The code is as follows:

type Manager interface {
    Add(name string) error
    Remove(name string) error
}
Copy after login

Here, we define a Manager interface, which contains the Add and Remove methods. Both methods accept a string type parameter name and return an error type value.

2. Implementation of interface

In Go, any type can implement an interface. The types here can be structures, basic data types, functions, etc. As long as a type implements all the methods defined by the interface, then the type can be considered to implement the interface.

The implementation of the interface can be done anywhere, that is, it can be done in the current package or in other packages. When a type implements an interface, it can be used in the caller's code without caring about the specific type.

For example, we can define a type MysqlManager to implement the Manager interface:

type MysqlManager struct {}

func (mm *MysqlManager) Add(name string) error {
    // Add logic handling here
    return nil
}
func (mm *MysqlManager) Remove(name string) error {
    // Remove logic handling here
    return nil
}
Copy after login

In the above code, we define a type MysqlManager, which implements the Manager interface, in the Add method The logic of adding data is implemented in the method, and the logic of deleting data is implemented in the Remove method. In this way, we can use the MysqlManager type instead of the Manager interface and use the Manager interface in the caller code.

Of course, we can also define a type RedisManager to implement the Manager interface:

type RedisManager struct {}

func (rm *RedisManager) Add(name string) error {
    // Add logic handling here
    return nil
}
func (rm *RedisManager) Remove(name string) error {
    // Remove logic handling here
    return nil
}
Copy after login

In the above code, we define a type RedisManager, which also implements the Manager interface. The logic of adding data is implemented in the Add method, and the logic of deleting data is implemented in the Remove method. In this way, we can choose to use different data sources according to different situations when actually using them, without caring about the specific type of data source.

3. Type conversion

Since the interface is not a specific type, it is just a collection of methods, so we need to perform type conversion when using it. The type conversion here is to convert the type that implements the interface into the interface type.

In Go, there are two forms of type conversion: one is forced type conversion, and the other is type assertion.

  1. Forced type conversion

When we convert a type that implements an interface into an interface type, we can use forced type conversion. The syntax format of this method is as follows:

var i interface{} = MysqlManager{}
mm := i.(Manager)
Copy after login

In the above code, we define a variable i, its type is interface{}, and then assign an instance of MysqlManager to it. Next, we use cast to convert i into the mm variable of the Manager interface type.

  1. Type assertion

In addition to forced type conversion, Go also provides another type conversion method called type assertion. The syntax format of type assertion is as follows:

var i interface{} = MysqlManager{}
mm, ok := i.(Manager)
Copy after login

In this example, we define a variable i, its type is interface{}, and then assign an instance of MysqlManager to it. Next, we use type assertions to try to convert i into the mm variable of the Manager interface type, and use the ok variable to determine whether the conversion is successful. If the conversion is successful, the value of ok is true, otherwise it is false.

4. Summary

In this article, we have an in-depth discussion of the definition and implementation of interfaces in the Go language. It can be seen that interface is a very important concept in Go, which can be used to implement polymorphism. In Go, any type can implement an interface, as long as it implements all methods defined by the interface. When a type implements an interface, it can be used in the caller's code without caring about the specific type. When using interfaces, we need to perform type conversion, which includes cast and type assertion.

The above is the detailed content of How are interfaces defined and implemented 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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
1 months ago By 尊渡假赌尊渡假赌尊渡假赌

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)

What is the problem with Queue thread in Go's crawler Colly? What is the problem with Queue thread in Go's crawler Colly? Apr 02, 2025 pm 02:09 PM

Queue threading problem in Go crawler Colly explores the problem of using the Colly crawler library in Go language, developers often encounter problems with threads and request queues. �...

What libraries are used for floating point number operations in Go? What libraries are used for floating point number operations in Go? Apr 02, 2025 pm 02:06 PM

The library used for floating-point number operation in Go language introduces how to ensure the accuracy is...

In Go, why does printing strings with Println and string() functions have different effects? In Go, why does printing strings with Println and string() functions have different effects? Apr 02, 2025 pm 02:03 PM

The difference between string printing in Go language: The difference in the effect of using Println and string() functions is in Go...

What is the difference between `var` and `type` keyword definition structure in Go language? What is the difference between `var` and `type` keyword definition structure in Go language? Apr 02, 2025 pm 12:57 PM

Two ways to define structures in Go language: the difference between var and type keywords. When defining structures, Go language often sees two different ways of writing: First...

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, ...

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...

Why is it necessary to pass pointers when using Go and viper libraries? Why is it necessary to pass pointers when using Go and viper libraries? Apr 02, 2025 pm 04:00 PM

Go pointer syntax and addressing problems in the use of viper library When programming in Go language, it is crucial to understand the syntax and usage of pointers, especially in...

See all articles