golang 类型切换中的多个案例

当我运行下面的代码片段时,它会引发错误


a.test undefined (type interface {} 是没有方法的接口)


看来类型切换没有生效。


package main


import (

    "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()

    }

现在好了。


天涯尽头无女友
浏览 126回答 1
1回答

胡子哥哥

这是规范定义的正常行为(强调我的):TypeSwitchGuard 可能包含一个简短的变量声明。当使用该形式时,变量在每个子句中隐式块的开头声明。在仅列出一种类型的 case 子句中,变量具有该类型;否则,变量具有 TypeSwitchGuard 中表达式的类型。所以,其实类型切换确实生效了,只是变量a保持了类型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()    }}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go