- 类型断言就是将接口类型的值
(x)
,转换成类型(T)
。格式为:x.(T)
; - 类型断言的必要条件就x是接口类型,非接口类型的x不能做类型断言;
- T可以是非接口类型,如果想断言合法,则T必须实现x的接口;
- T也可以是接口,则x的动态类型也应该是接口T;
- 类型断言如果非法,运行时会导致错误,为了避免这种错误,应该总是使用下面的方式来进行类型断言
package main
import (
"fmt"
)
func main() {
var x interface{}
x =100
value1,ok :=x.(int)
if ok {
fmt.Println(value1)
}
value2,ok :=x.(string)
if ok {
fmt.Println(value2)
}
}
需要注意的如果不接收第二个参数也就是ok
,这里失败的话则会直接panic
这里还存在一种情况就是x
为nil
同样会panic
- 类型不对的情况:
package main
import "fmt"
func main() {
var x interface{}
x ="hello"
value :=x.(int)
fmt.Println(value)
}
x
为nil
:
package main
import "fmt"
func main() {
var x interface{}
//x ="hello"
value :=x.(int)
fmt.Println(value)
}
若类型检查成功提取到的值也将拥有对应type的方法:
package main
import "fmt"
func main() {
var a interface{}
a =A{}
value :=a.(A)
value.Hi()
fmt.Println("看是否输出",value.Name)
}
type A struct {
Name string
}
func (a A)String() string {
return "Type Is A"
}
func (a *A) Hi() {
a.Name="fushaohua"
fmt.Println(a)
}
switch
package main
import "fmt"
func main() {
n :=100
JudgeType(n)
str :="Hello World"
JudgeType(str)
a :=A{}
JudgeType(a)
a1 :=new(A)
JudgeType(a1)
}
func JudgeType(a interface{}) {
switch value :=a.(type) {
case nil:
fmt.Println("Type is nil")
case int:
fmt.Println("int:",value)
case string:
fmt.Println("string",value)
case A:
fmt.Println("类型A",value)
case *A:
fmt.Println("指针A",value)
default:
fmt.Println("未匹配")
}
}
type A struct {
}
func (a A)Strubg()string {
return "Type Is A"
}
输出:
int: 100
string: Hello World
类型A: Type Is A
指针A Type Is A