Home  >  Article  >  Backend Development  >  An article to help you understand the basic interface of Go language (Part 2)

An article to help you understand the basic interface of Go language (Part 2)

Go语言进阶学习
Go语言进阶学习forward
2023-07-20 17:24:121426browse

The meaning of empty interface

This article introduces Storage class interface , storage interface is my name. In fact, others call it empty interface.

The function of the empty interface is to store any data.

Similarly, the empty interface does not define any methods, that is to say any Interfaces all implement empty interfaces, so empty interfaces can save any data.


Empty interface

##Empty interface sample code

package main

import "fmt"

func main() {
    //变量直接赋值为空接口
    var x interface{}
    x = 1
    x = 1.1
    x = "666"
    x = [3]int{1, 2, 3} //数组
    x = []int{6, 23}    //切片
    x = map[string]string{
        "Name": "张三",
        "Age":  "666",
}
    fmt.Println(x)
    //map中value类型为空接口
    var y = map[string]interface{}{
        "Name":"张三",
        "Age":18,
}
    fmt.Println(y)
}

Execution results

An article to help you understand the basic interface of Go language (Part 2)

##The empty interface can indeed store any data and can be used directly.


空接口在函数中的应用

不知道你有没有想过,如果函数的参数,也是一个空接口,那不是就可以随便传值了吗?

我还用个毛静态类型,以后都用空接口得了,嗯。。。这个按下不表,等会说。


函数参数为空接口代码

package main
import "fmt"

func say(x interface{}) {
    fmt.Println(x)
}
func main() {
    say(1)
    say("666")
    say([]int{5, 1, 3})
}

确实是如上述所说,函数参数为空接口类类型,的确可以传任何数据。

但是仅限打印时可以随便打印。

假设我想让传入的值+1

func say(x interface{}) {
    fmt.Println(x)
    fmt.Println(x+1)
}

报错信息

An article to help you understand the basic interface of Go language (Part 2)

所以说,空接口并不是万能的。


类型断言

上述函数虽然可以接收任意类型。

但是我有个需求。

如果传入的是int类型,参数+100。

如果传入的是字符串类型,参数+"666"。

如果传入的是其他类型,返回不存在。

这该怎么办呢?这就要用到断言这个功能。

断言语法

空接口.(类型)

示例代码

func say(x interface{}) {
    value, ok := x.(int)
    if ok {
        //如果是ok表示断言成功,是int类型
        fmt.Println(value + 100)
}
    value2, ok := x.(string)
    if ok {
        //断言成功表示是字符串
        fmt.Println(value2 + "666")
  }
}

如果说有很多类型,断言起来比较麻烦,这时候用switch比较好。

func say(x interface{}) {
    switch value := x.(type) {
    case int:
        fmt.Println(value + 10)
    case string:
        fmt.Println(value + "666")
    default:
        fmt.Println("啥都不是")
  }
}
//case可以继续写,可以写很多很多

执行结果

An article to help you understand the basic interface of Go language (Part 2)


总结

到此为止,Go语言的接口是全部都讲完了。

接口主要分为行为接口存储接口

  • 行为接口主要用在面向对象这个方向,规定父类必须有哪些动作。

  • 空接口时为了方便存值,可以存储任意类型。

The above is the detailed content of An article to help you understand the basic interface of Go language (Part 2). For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:Go语言进阶学习. If there is any infringement, please contact admin@php.cn delete