golang 类型断言为什么一个值会有两种类型?

新手上路,请多包涵

做测试的时候发现,使用golang 类型断言的时候一个值有两种类型。

package main

import (

"fmt"

)

type Describer interface {

Describe()

}
type St string

func (s St) Describe() {

fmt.Println("被调用le!")

}

func findType(i interface{}) {

switch v := i.(type) {
case St:
    fmt.Println("Hello world!")
case Describer:
    v.Describe()
    fmt.Println("hello")
case string:
    fmt.Println("String 变量")
default:
    fmt.Printf("unknown type\n")
}

}

func main() {

findType("Naveen")
fmt.Println("###########################")
st := St("我的字符串")
findType(st)

}

当最后一次调用 findType(st)时 , 如果 case St 存在,则输出结果为 Hello world! 如果注释掉 case St , 则输出为 被调用le hello , 那么说明, st既是St类型, 又是Desceiber类型。请问为什么会这样呢?

阅读 2.3k
2 个回答

golang隐式实现接口,你的St实现了Describer接口,当然算可以匹配到这个case分支了。

代码里做了两个事情

  1. 常见一个string的别名类型 St 类型
  2. 让St类型实现Describer的接口

当St实现了接口后,在类型判断时,他就满足接口类型了,所以在第一个case判断时通过