断言的定义
go中有一个语法,可以直接判断一个变量是否是该类型:
value,ok = element.(T)
,这里value就是变量的值,ok是一个bool类型,element是interface变量,T是断言的类型.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48
| type Inter interface{say()} type Chinese struct{}
func (c Chinese) say(){ fmt.Println("chinese say") }
func (c Chinese) run(){ fmt.Println("跳大神") } type Amrican struct{} func (c Amrican) say(){ fmt.Println("Amrican say") }
func play(i Inter){ i.say() if ch,flag := i.(Chinese);flag{ fmt.Println("成功了") ch.run() }else{ fmt.Println("失败了") } switch i.(type){ case Chinese: ch := i.(Chinese) ch.run() case Amrican: us := i.(Amrican) us.disco() } } func main(){ var c Chinese = Chinese{} var a Amrican = Amrican{} play(c) play(a) fmt.Println("exit...") }
|