doukui4836 2019-09-17 22:21
浏览 148
已采纳

如何检查Go接口类型的变量是否具有实现它的某些结构类型?

Lets say that I have the following:

type A Interface{
   ....
}

//Implements A
type B struct{
   ....
}

//Imlements A
type C struct{
   ....
}

And now I have a function which accepts variable of type A as an argument:

func Foo(obj A){
     if A is B{
          ....
     }else if A is C{
          ....
     }
}

And a main function:

func main(){

    b := B{}
    Foo(b)

}

How can I check if the argument passed to the function is actually type B?

  • 写回答

1条回答 默认 最新

  • douzi4766 2019-09-18 00:50
    关注

    Use a type switch as mentioned the tour page linked by @CeriseLimón.

    func Foo(v A) {
        switch v := v.(type) {
        case B:
            // It's a B
        case C:
            // It's a C
        }
    }
    

    See it in action in the playground.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 delta降尺度方法,未来数据怎么降尺度
  • ¥15 c# 使用NPOI快速将datatable数据导入excel中指定sheet,要求快速高效
  • ¥15 高德地图点聚合中Marker的位置无法实时更新
  • ¥15 DIFY API Endpoint 问题。
  • ¥20 sub地址DHCP问题
  • ¥15 delta降尺度计算的一些细节,有偿
  • ¥15 Arduino红外遥控代码有问题
  • ¥15 数值计算离散正交多项式
  • ¥30 数值计算均差系数编程
  • ¥15 redis-full-check比较 两个集群的数据出错