类型断言的定义
我们直接通过一个案例来描述类型断言比较直观
package main
import(
"fmt"
)
type Point struct {
X int
Y int
}
func main() {
var point Point = Point{1, 2}
var a interface{}
a = point
var b Point
//b = a // 这种写法是有问题的,不能直接将一个接口类型赋值给一个自定义类型
// 这句话的意思是,判断a是否指向Point类型,若指向,则转成Point类型,这就是类型断言
b = a.(Point)
}
类型断言同样可以用于基础数据类型,如果断言的数据类型不匹配,会报panic,如果我们想在断言时带检查而不报panic,需要这样写即可:
b, is_ok = a.(Point)
if is_ok {
} else {
}
类型断言的应用场景
- 类似前面文章提到过的结构体切片,存储不同的结构体变量,如果我们想根据不同的变量调用类型特有的方法,这时就需要用到类型断言。
type Usb interface{
Start()
Stop()
}
type Phone struct{}
type Camera struct()
func (p Phone) Start(){
}
func (p Phone) Stop() {
}
// Call()为Phone独有
func (p Phone) Call() {
}
func (p Camera) Start(){
}
func (p Camera) Stop() {
}
type Computer struct{
}
func (c computer) Write(usb Usb) {
usb.Start()
// 判断usb为Phone时,调用Call()
if phone, ok := usb.(Phone); ok {
phone.Call()
}
usb.Stop()
}
func ()
- 用于判断参数类型,典型案例如写一个函数,可以接收任意个数的参数,判断对应的参数类型
func TypeJudge(items... {}interface) {
for index, x := range items {
switch(x.(type) {
case bool:
// ...
case int, int64:
// ...
case string:
// ...
case Student:
// ...
case *Student:
// ...
default:
//...
}
}
}
有意思的是,自定义类型Student可以在上面函数之后再定义,但一般不推荐这样做