duannuan0074 2016-11-13 14:42
浏览 194
已采纳

golang多种类型的开关

when I run the code snippet bellow, it raise a error

a.test undefined (type interface {} is interface with no methods)

It seem the type switch does not take effect.

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

If I change it to

    switch a := foo.(type){
        case A:
            a.test()
    }

it's ok now.

  • 写回答

1条回答 默认 最新

  • dongshilve4392 2016-11-13 14:45
    关注

    This is normal behaviour that is defined by the spec (emphasis mine):

    The TypeSwitchGuard may include a short variable declaration. When that form is used, the variable is declared at the beginning of the implicit block in each clause. In clauses with a case listing exactly one type, the variable has that type; otherwise, the variable has the type of the expression in the TypeSwitchGuard.

    So, in fact, the type switch does take effect, but the variable a keeps the type interface{}.

    One way you could get around this is to assert that foo has the method test(), which would look something like this:

    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()
        }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 我要一个分身加定位两个功能的安卓app
  • ¥15 基于FOC驱动器,如何实现卡丁车下坡无阻力的遛坡的效果
  • ¥15 IAR程序莫名变量多重定义
  • ¥15 (标签-UDP|关键词-client)
  • ¥15 关于库卡officelite无法与虚拟机通讯的问题
  • ¥15 目标检测项目无法读取视频
  • ¥15 GEO datasets中基因芯片数据仅仅提供了normalized signal如何进行差异分析
  • ¥100 求采集电商背景音乐的方法
  • ¥15 数学建模竞赛求指导帮助
  • ¥15 STM32控制MAX7219问题求解答