Home  >  Article  >  Backend Development  >  Can go language develop interfaces?

Can go language develop interfaces?

青灯夜游
青灯夜游Original
2022-12-15 18:49:415414browse

Go language can develop interfaces. The interface in the Go language is the signature of a set of methods. It is an important part of the Go language. What the interface does is like defining a specification or protocol. Each implementing party only needs to implement it according to the protocol. The interface keyword is used in the go language to define the interface. The syntax is "type interface type name interface{method name 1 (parameter list 1) return value list 1 method name 2 (parameter list 2) return value list 2...}".

Can go language develop interfaces?

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

Interface should be a familiar concept to us. It is widely used in various development languages. For programmers like us who are more familiar with Java, interfaces are more familiar. The following Let’s take a look at how interfaces are used in the Go language and the role they play in daily development.

Concept

The interface in the Go language is the signature of a set of methods. It is an important part of the Go language. What the interface does is like defining a specification. Or agreement, each implementing party only needs to implement it according to the agreement.

Interface is a type

Interface type is an abstraction and generalization of the behavior of other types. It does not care about specific implementation details. This abstract method can make our functions more flexible. .

Interface definition

type 接口类型名 interface{
    方法名1( 参数列表1 ) 返回值列表1
    方法名2( 参数列表2 ) 返回值列表2
    …
}

In the go language we use the interface keyword to define the interface.

Interface implementation conditions

If the method set of any type T is a superset of the method set of an interface type, then we say that type T implements the interface.

The implementation of the interface is implicit in the Go language, which means that the implementation relationship between the two types does not need to be reflected in the code. There is no keyword similar to the implements in Java in the Go language. Go The compiler will automatically check the implementation relationship between two types when needed. After the interface is defined, it needs to be implemented so that the caller can correctly compile and use the interface.

The implementation of the interface needs to follow two rules to make the interface available:

1. The methods of the interface are in the same format as the type method that implements the interface. Just add a method consistent with the interface signature in the type. Implement this method. The signature includes the name, parameter list, and return parameter list of the method. In other words, as long as any item in the name, parameter list, and return parameter list of the method in the implemented interface type is inconsistent with the method to be implemented by the interface, then this method of the interface will not be implemented.

package main

import "fmt"

type Phone interface {
	Call()
	SendMessage()
}

type HuaWei struct {
	Name  string
	Price float64
}

func (h *HuaWei) Call() {
	fmt.Printf("%s:可以打电话",h.Name)
}

func (h *HuaWei) SendMessage() {
	fmt.Printf("%s:可以发送短信",h.Name)
}

func main() {

	h := new(HuaWei)
	h.Name="华为"
	var phone Phone
	phone = h
	phone.SendMessage()
}

When a type cannot implement an interface, the compiler will report an error:

a. Errors caused by inconsistent function names

b. Errors caused by inconsistent method signatures to implement functions

2. All methods in the interface are implemented. When there are multiple methods in an interface, only if these methods are implemented can the interface be compiled and used correctly

func (h *Xiaomi) Call() {
	fmt.Printf("%s:可以打电话",h.Name)
}

func main() {
	h := new(Xiaomi)
	h.Name="小米"
	var phone Phone
	phone = h
	phone.SendMessage()
}

Can go language develop interfaces?

When the Xiaomi type only implements one method in the interface, a compilation error will be reported when we use it.

The relationship between types and interfaces

A type implements multiple interfaces

A type can implement multiple interfaces, and the interfaces are independent of each other and do not know the implementation of each other.

For example, a dog can move and be called

package main

import "fmt"

type Move interface {
	move()
}
type Say interface {
	say()
}
type Dog struct {
	Name string
}

func (d *Dog) move()  {
	fmt.Printf("%s会动\n", d.Name)
}
func (d *Dog) say()  {
	fmt.Printf("%s会叫汪汪汪\n", d.Name)
}

func main() {
	var m Move
	var s  Say
	d:=&Dog{
		Name: "旺财",
	}
	m = d
	s=d
	m.move()
	s.say()
}

Multiple types implement the same interface

In Go language Different types can also implement the same interface. First we define a Mover interface, which requires a move method.

type Mover interface {
    move()
}

For example, dogs can move, and cars can also move. You can use the following code to achieve this relationship:

type dog struct {
    name string
}

type car struct {
    brand string
}

// dog类型实现Mover接口
func (d dog) move() {
    fmt.Printf("%s会跑\n", d.name)
}

// car类型实现Mover接口
func (c car) move() {
    fmt.Printf("%s速度70迈\n", c.brand)
}

At this time, we can treat dogs and cars as one moving object in the code To deal with it, you no longer need to pay attention to what they are, you only need to call their move method.

func main() {
        var x Mover
        var a = dog{name: "旺财"}
        var b = car{brand: "保时捷"}
        x = a
        x.move()
        x = b
        x.move()
    }

Empty interface

Empty interface: interface{}, does not contain any methods. Because of this, any type implements the empty interface, so the empty interface can be stored Any type of data.

fmt The Print series of functions under the package, most of their parameters are empty interface types, it can also be said to support any type

func Print(a ...interface{}) (n int, err error)
func Println(format string, a ...interface{}) (n int, err error)
func Println(a ...interface{}) (n int, err error)

The empty interface is used as The value of map

// 空接口作为map值
    var studentInfo = make(map[string]interface{})
    studentInfo["name"] = "李白"
    studentInfo["age"] = 18
    studentInfo["married"] = false
    fmt.Println(studentInfo)

Type inference

The empty interface can store any type of value, so how do we get the specific data it stores?

Interface value

The value of an interface (referred to as interface value) is composed of a specific type and the value of the specific type.

These two parts are called the dynamic type and dynamic value of the interface respectively.

If you want to judge the value in the empty interface, you can use type assertion. Its syntax format is:

x.(T)

Among them:

  • x: means A variable of type interface{}

  • T: represents the type that the assertion x may be.

该语法返回两个参数,第一个参数是x转化为T类型后的变量,第二个值是一个布尔值,若为true则表示断言成功,为false则表示断言失败。

func main() {
    var x interface{}
    x = "ms的go教程"
    v, ok := x.(string)
    if ok {
        fmt.Println(v)
    } else {
        fmt.Println("类型断言失败")
    }
}

 上面的示例中如果要断言多次就需要写多个if判断,这个时候我们可以使用switch语句来实现:

func justifyType(x interface{}) {
    switch v := x.(type) {
    case string:
        fmt.Printf("x is a string,value is %v\n", v)
    case int:
        fmt.Printf("x is a int is %v\n", v)
    case bool:
        fmt.Printf("x is a bool is %v\n", v)
    default:
        fmt.Println("unsupport type!")
    }
}

因为空接口可以存储任意类型值的特点,所以空接口在Go语言中的使用十分广泛。

总结

关于接口需要注意的是,只有当有两个或两个以上的具体类型必须以相同的方式进行处理时才需要定义接口。不要为了接口而写接口,那样只会增加不必要的抽象,导致不必要的运行时损耗。

【相关推荐:Go视频教程编程教学

The above is the detailed content of Can go language develop interfaces?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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