当我运行下面的代码片段时,它会引发错误a.test undefined (type interface {} 是没有方法的接口)看来类型切换没有生效。package mainimport ( "fmt")type A struct { a int}func(this *A) test(){ fmt.Println(this)}type B struct { A}func main() { var foo interface{} foo = A{} switch a := foo.(type){ case B, A: a.test() }}如果我将其更改为 switch a := foo.(type){ case A: a.test() }现在好了。
1 回答

胡子哥哥
TA贡献1825条经验 获得超6个赞
这是规范定义的正常行为(强调我的):
TypeSwitchGuard 可能包含一个简短的变量声明。当使用该形式时,变量在每个子句中隐式块的开头声明。在仅列出一种类型的 case 子句中,变量具有该类型;否则,变量具有 TypeSwitchGuard 中表达式的类型。
所以,其实类型切换确实生效了,只是变量a保持了类型interface{}。
解决此问题的一种方法是断言具有foo方法test(),它看起来像这样:
package main
import (
"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()
}
}
- 1 回答
- 0 关注
- 124 浏览
添加回答
举报
0/150
提交
取消