本文介绍Go类型推断以及使用示例。类型推断用于获取存储在interface种变量类型及其值。
为什么需要类型推断
我们知道空interface可以接收任意类型值,举例:
// create an empty interface
var a interface {}
// store value of string type
a = "Hello World"
// store value of integer type
a = 10
这里a为空interface,它既能存储字符串,也能存储整型。这是空接口类型的重要特性,但有时也造成无法确切知道接口中存储变量的具体类型,为了解决该问题,可以使用类型推断。
类型推断
package main
import "fmt"
func main() {
// create an empty interface
var a interface {}
// store integer to an empty interface
a = 10
// type assertion
interfaceValue := a.(int)
fmt.Println(interfaceValue)
// 输出 10
}
下面解释这行代码:
interfaceValue := a.(int)
(int) 检查a的值是否为整型,如果是,返回a的值给interfaceValue.否则程序报错并终止。
package main
import "fmt"
func main() {
// create an empty interface
var a interface{}
// store integer to an empty interface
a = "Golang"
// type assertion
interfaceValue := a.(int)
fmt.Println(interfaceValue)
}
这里空接口值为字符串,a.(int)不为true,因此报错。输出错误信息:
panic: interface conversion: interface {} is string, not int
避免报错
Go类型推断支持返回多个值,从而避免程序报错,下面代码除了返回值,还有另一个布尔值标识是否类型匹配:
package main
import "fmt"
func main() {
// create an empty interface
var a interface{}
a = 12
// type assertion
interfaceValue, booleanValue := a.(int)
fmt.Println("Interface Value:", interfaceValue)
fmt.Println("Boolean Value:", booleanValue)
}
输出:
Interface Value: 12
Boolean Value: true
再看一个不匹配场景:
package main
import "fmt"
func main() {
// create an empty interface
var a interface{}
a = "Golang"
// type assertion
interfaceValue, booleanValue := a.(int)
fmt.Println("Interface Value:", interfaceValue)
fmt.Println("Boolean Value:", booleanValue)
}
输出:
Interface Value: 0
Boolean Value: false
类型不匹配时,仅返回值为false,程序并没报错。
类型选择(Type Switch)
类型选择用于与switch语句中多个case 类型比较接口的具体类型。它与单个类型推断有点差别,case后面是具体类型,而不是值。示例代码如下:
// Go program to illustrate type switch
package main
import "fmt"
func myfun(a interface{}) {
// Using type switch
switch a.(type) {
case int:
fmt.Println("Type: int, Value:", a.(int))
case string:
fmt.Println("\nType: string, Value: ", a.(string))
case float64:
fmt.Println("\nType: float64, Value: ", a.(float64))
default:
fmt.Println("\nType not found")
}
}
// Main method
func main() {
myfun("GeeksforGeeks")
myfun(67.9)
myfun(true)
}
输出结果:
Type: string, Value: GeeksforGeeks
Type: float64, Value: 67.9
Type not found