golang多种类型的开关
当我运行下面的代码片段时,它会引发错误
a.test未定义(类型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()
    }
没关系
回答:
这是规范(强调我的)定义的正常行为:
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()
    }
}
以上是 golang多种类型的开关 的全部内容, 来源链接: utcz.com/qa/415432.html







