做测试的时候发现,使用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类型。请问为什么会这样呢?
golang隐式实现接口,你的St实现了Describer接口,当然算可以匹配到这个case分支了。