Home > Backend Development > Golang > Introduction to the usage of Go interface interface

Introduction to the usage of Go interface interface

Release: 2020-02-17 17:17:55
forward
2804 people have browsed it

The interface of go is used very frequently in go programming, especially the use of empty interface. Because of the interface, the Go language becomes extremely powerful. go language tutorial column will introduce to you the usage of Go interface interface.

Introduction to the usage of Go interface interface

About the concept of interface:

1. An interface is a collection of one or more method signatures

2. As long as a certain type With all the method signatures of the interface, even if the interface is implemented, there is no need to show which interface the declaration implements. This is called Structural Typing

3. The interface only has method declarations, no implementation, and no data structure fields

4. Interfaces can be embedded anonymously into other interfaces, or into interfaces

5. When an object is copied to an interface, a copy will occur, and what is stored inside the interface is a pointer to the copy, that is The status of the replica cannot be modified, nor can the pointer be obtained

6. Interface calls will not automatically convert the receiver

7. Interfaces can also implement polymorphism similar to OOP

8. The empty interface can be used as a container for any type of data

Now let’s introduce the most basic interface. Introduce concept 2

package main
 
import (
	"fmt"
)
type USB interface {   // 定义一个USB接口 ,该接口拥有PhoneConnect的所有方法签名,
	Name() string       //即就实现了PhoneConnect的接口,无需在声明。这就是上面说的第2条
	Connect()
}
type PhoneConnect struct {   //定义的结构体
	name string
}
func (pc PhoneConnect) Name() string{  //上面结构体的方法
	return pc.name
}
func (pc PhoneConnect) Connect(){
	fmt.Println("Connectd to: ",pc.name)
}
 
func main(){    
	var a USB      //声明该接口
	a = PhoneConnect{"IPhone"}  //该接口已经支持PhoneConnect这个结构体了。初始化该结构体
	a.Connect()     //调用该结构体的Connect方法
}
Copy after login

If you understand the above example, then read on.

Define another function to receive parameters of USB type. Pass a in. In fact, a can already call all methods of phoneConnect. And at this time, I made the statement of a a little vague.

func Disconnect(usb USB){
	fmt.Println("Discounnectd from:",usb.Name())
}
func main(){
	a := PhoneConnect{"IPhone"}  //a是什么类型呢?
	fmt.Println("type:",reflect.TypeOf(a))
	Disconnect(a)
}
Copy after login

Look at the running results:

type: main.PhoneConnect
Discounnectd from: IPhone

a is an instantiated PhoneConnect type structure, but the Disconnect function requires receiving a USB type data, a can be passed in! ! !

Let’s take a look at Concept 7:

type USB interface {   // 定义一个USB接口 ,该接口拥有PhoneConnect的所有方法签名,
	Name() string       //
	Connect             //嵌入了一个Connect接口,效果和最开始演示的是一样的
}
type Connect interface {
	Connect()
}
Copy after login

Any structure that satisfies the Name() and Connect() methods can be regarded as a USB. Is there something wrong? What if the USB I pass in to the DisConnect() function is not a mobile phone? ? Just use an ok-pattern. For example, I add a TV structure, and the TV also has a USB interface.

type TVConnect struct {
	name string
}
func (tc TVConnect) Name() string{
	return tc.name
}
func (tc TVConnect) Connect() {
	fmt.Println("Connect to: ",tc.name)
}
func Disconnect(usb USB){
	if rs,ok := usb.(PhoneConnect);ok{
		fmt.Println("Disconnect: ",rs.name)
	}else{
		fmt.Println("Unknown device: ")
	}
}
func main(){
	a := PhoneConnect{"IPhone"}
	b := TVConnect{"ChuangWei"}
	Disconnect(a)
	Disconnect(b)
}
Copy after login

Look at the print result:

Disconnect: IPhone
Unknown device:

b is a USB interface of Skyworth TV , but b is not recognized in the Disconnect function because it is a TV.

Advanced again. Since you can determine the structure of the incoming data in the Disconnect function, you don't need to worry about the USB interface type anymore. Directly define it as an empty interface. Otherwise, it’s over. Anyway, I’m trying to determine what type you are in the function.

func Disconnect(usb interface{}){   //注意,这里是空接口
	switch v:=usb.(type) {
	case PhoneConnect:
		fmt.Println(" Phone device Disconnected from",v.name)
	case TVConnect:
		fmt.Println("TV device Disconnected from",v.name)
	default:
		fmt.Println("Unknown device ...")
	}
}
func main(){
	a := PhoneConnect{"IPhone"}
	b := TVConnect{"ChuangWei"}
	Disconnect(a)
	Disconnect(b)
}
Copy after login

Look at the printing situation:

Phone device : Disconnected from IPhone
TV device : Disconnected from ChuangWei

More For go language knowledge, please pay attention to the go language tutorial column on the PHP Chinese website.

The above is the detailed content of Introduction to the usage of Go interface interface. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
go
source:csdn.net
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template