接口类型推断
什么是接口类型推断
-
如果一个类型实现了接口,那么接口类型变量里面就可以存储该类型的数据,把实现接口功能的对象插入到接口中
-
那么如何反向直到接口类型变量里面实际保存的是哪一种类型的对象呢?这就是接口类型推断
-
两种方法
comma-ok
断言- switch测试
-
类型断言就是将接口类型的值
(x)
,装换成类型(T)
。格式为:x.(T) v:=x.(T) v,ok:=x.(T)
-
T
可以是非接口类型,如果想断言合法,则T
应该实现x
的接口
package main
import (
"fmt"
)
type point struct {
x int
y int
}
func main() {
var a interface{
}
var q point = point{
1, 2}
a = q
var b point
b = a.(point)//类型断言
/*
判断a是否指向point类型的变量,
如果是,将a转为point类型变量,并赋给b
否则报错
*/
fmt.Println(b)
}
comma-ok
- e.(指定数据类型):查询e是否为指定类型,结果为val,
ok
形式。val为e的取值,ok
为是不是指定数据类型,供if判断用
package main
import (
"fmt"
)
//Stu 类
type Stu struct {
name string
age int
}
//Tester 空接口定义,存储任意类型
type Tester interface{
}
func main() {
p := make([]Tester, 4)
p[0] = 1
p[1] = "pass the exam"
p[2] = true
p[3] = Stu{
"独孤求败", 99}
for i, e := range p {
//comma-ok类型推断
if val, ok := e.(int); ok {
fmt.Printf("p[%d] type is int,val =%d\n", i, val)
}
if val, ok := e.(string); ok {
fmt.Printf("p[%d] type is string,val =%s\n", i, val)
}
if val, ok := e.(bool); ok {
fmt.Printf("p[%d] type is bool,val =%t\n", i, val)
}
if val, ok := e.(Stu); ok {
fmt.Printf("p[%d] type is Stu,val =%v\n", i, val)
}
}
}
p[0] type is int,val =1 p[1] type is string,val =pass the exam p[2] type is bool,val =true p[3] type is Stu,val ={独孤求败 99}
switch 模式
- e.(type):查询e的数据类型,不能在switch语句外的任何逻辑语句里使用。
package main
import (
"fmt"
)
//Stu 类
type Stu struct {
name string
age int
}
//Tester 空接口定义,存储任意类型
type Tester interface{
}
func main() {
p := make([]Tester, 4)
p[0] = 1
p[1] = "pass the exam"
p[2] = true
p[3] = Stu{
"独孤求败", 99}
for i, e := range p {
//switch
switch val := e.(type) {
case int:
fmt.Printf("p[%d] type is int,val =%d\n", i, val)
case string:
fmt.Printf("p[%d] type is string,val =%s\n", i, val)
case bool:
fmt.Printf("p[%d] type is bool,val =%t\n", i, val)
case Stu:
fmt.Printf("p[%d] type is Stu,val =%v\n", i, val)
}
}
}
p[0] type is int,val =1 p[1] type is string,val =pass the exam p[2] type is bool,val =true p[3] type is Stu,val ={独孤求败 99}
- 接口切片可以看作多态数组,即数组中的元素类型可以不相同