Go语言类型断言简述
func test1(arg interface{}) { value, ok := arg.(string) // 类型断言 if ok { fmt.Println(value) } else { fmt.Println("类型错误") } fmt.Println(arg) }
在Go语言中类型断言的语法格式如下:
value, ok := x.(T)
其中,x 表示一个接口的类型,T 表示一个具体的类型(也可为接口类型)。
该断言表达式会返回 x 的值(也就是 value)和一个布尔值(也就是 ok),可根据该布尔值判断 x 是否为 T 类型:
- 如果 T 是具体某个类型,类型断言会检查 x 的动态类型是否等于具体类型 T。如果检查成功,类型断言返回的结果是 x 的动态值,其类型是 T。
- 如果 T 是接口类型,类型断言会检查 x 的动态类型是否满足 T。如果检查成功,x 的动态值不会被提取,返回值是一个类型为 T 的接口值。
- 无论 T 是什么类型,如果 x 是 nil 接口值,类型断言都会失败。
- 一个变量的内容是包含两个部分的,分别是 type 和 value 对
- type 又分为静态类型和运行时的具体类型
type Reader interface { read() } type Writer interface { write() } type Some struct { } func (s *Some) write() { fmt.Println("我有写的方法") } func (s *Some) read() { fmt.Println("我有读的方法") } func main() { s := &Some{} s.read() var t Reader t = s // s 赋值给t 也就是将 pair给了t w := t.(Writer) w.write() // w.read()
如果新增一个接口类型, 并将 t 更改成这个新类型呢
type Reader interface { read() } type Writer interface { write() } type Fuck interface { fuck() } type Some struct { } func (s *Some) write() { fmt.Println("我有写的方法") } func (s *Some) read() { fmt.Println("我有读的方法") } func main() { s := &Some{} s.read() var t Fuck t = s // cannot use s (variable of type *Some) as Fuck value in assignment: missing method fuckcompiler w := t.(Writer) w.write() // w.read() }
这里懵逼了, 难道长得象鸭子的最后都可以成为鸭子