这是规范(强调我的)定义的正常行为:
TypeSwitchGuard可以包含一个简短的变量声明。使用该格式时,将在每个子句中隐式块的开头声明变量。
在大小写正好列出一种类型的子句中,变量具有该类型。 否则,变量具有TypeSwitchGuard中表达式的类型。
因此,实际上,类型开关确实有效,但是变量
a保留type
interface{}。你能解决这个问题的方法之一是断言的是
foo有方法
test(),这将是这个样子:
package mainimport ( "fmt")type A struct { a int}func (this *A) test() { fmt.Println(this)}type B struct { A}type tester interface { test()}func main() { var foo interface{} foo = &B{} if a, ok := foo.(tester); ok { fmt.Println("foo has test() method") a.test() }}


