为了账号安全,请及时绑定邮箱和手机立即绑定

golang 类型切换中的多个案例

golang 类型切换中的多个案例

Go
天涯尽头无女友 2022-04-20 17:52:17
当我运行下面的代码片段时,它会引发错误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()

    }

}


查看完整回答
反对 回复 2022-04-20
  • 1 回答
  • 0 关注
  • 124 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号