interface{} 万能类型

  • Golang 的各种预置的变量类型int string等等都是实现了interface{}
  • interface{} 是一个万能类型,万能类型可以接收任意的类型,可以用它实现很多业务
package main

import "fmt"

func MyFunc(arg interface{}) {
	fmt.Println("my func is called")
	fmt.Println(arg)
}

type Book struct {
	name string
}

func main() {
	book1 := Book{"test"}
	MyFunc(book1)
	MyFunc("this is a string")
	MyFunc(12345)
	MyFunc(1.414)
}
// 输出结果
my func is called
{test}
my func is called
this is a string
my func is called
12345
my func is called
1.414

类型断言机制

  • 对于万能类型,go提供了一种叫类型断言的东西。它可以帮助你判断 interface{} 具体接收了什么类型的对象。
  • 语法是 arg.(type),它有两个返回值,一个是接收对象的值,一个是判断是否为type类型,是返回true,否则为false
package main

import "fmt"

func MyFunc(arg interface{}) {
	fmt.Println("my func is called")
	value, ok := arg.(string)
	if !ok {
		fmt.Println("this is not a string")
	} else {
		fmt.Println(value)
	}

}

type Book struct {
	name string
}

func main() {
	book1 := Book{"test"}
	MyFunc(book1)
	MyFunc("this is a string haha")
	MyFunc(12345)
	MyFunc(1.414)
}
PS D:\StudyCode\GoLand\HelloWorld> go run .\test.go
my func is called
this is not a string
my func is called
this is a string haha
my func is called
this is not a string
my func is called
this is not a string