golang多种类型的开关 [英] golang multiple case in type switch

查看:188
本文介绍了golang多种类型的开关的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我运行代码片段时,它引发一个错误:
$ b


a.test undefined(type interface {}方法)

看起来类型切换不起作用。



<$ p









$ b $

$ b func(this * A)test(){
fmt.Println(this)
}

type B struct {


$ b $ func main(){
var foo interface {}
foo = A {}
switch a:= foo 。(type){
case B,A:
a.test()
}
}

如果将其更改为

 切换a:= foo。(type) {
案例A:
a.test()
}

解决方案

这是由规格(强调我的):
$ b blockquote>

TypeSwitchGuard可能包含一个简短的变量声明。当使用该表单时,该变量将在每个子句中的隐式块的开始处声明。 在具有一种类型的案例列表中,该变量具有该类型;否则,该变量具有TypeSwitchGuard中表达式的类型


因此,事实上,类型开关确实生效,但变量 a 保持类型界面{}



解决这个问题的一种方法是断言 foo 的方法 test(),它看起来像这样:

< pre $







$ b $ struct $ {
a int

$ b $ func(this * A)test(){
fmt.Println(this)
}

type B struct {
A
}

类型测试器接口{
test()
}

func main(){
var foo interface {}
foo =& B {}
如果a,ok:= foo。(tester); OK {
fmt.Println(foo has test()method)
.test()
}
}


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.

解决方案

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

这篇关于golang多种类型的开关的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆