drpph80800 2017-10-14 18:07
浏览 84
已采纳

如何在Go中获取继承结构的属性?

In Go,

type PacketType1 struct {
    myValue string
}
type PacketType2 struct {
    myValue2 string
}

Can I pass these generically and then check the type somehow? I looked into interfaces, however those seem to be for inheriting functions. Based on the names, this is for a packet system, how could I pass any of these packets to a function as an argument, check the type, and get properties of structs, etc. If this isn't possible, then how would I best implement a packet system in Go?

  • 写回答

1条回答 默认 最新

  • duanmei1850 2017-10-14 19:06
    关注

    It is possible to pass the value as an interface{}, then use a type switch to detect which type was passed. Alternatively you can create an interface that exposes the common functionality you need and simply use that.

    Interface and type switch:

    func Example(v interface{}){
        switch v2 := v.(type) {
        case PacketType1:
            // Do stuff with v1 (which has type PacketType1 here)
        case PacketType2:
            // Do stuff with v1 (which has type PacketType2 here)
        }
    }
    

    Common interface:

    type Packet interface{
        GetExample() string
        // More methods as needed
    }
    
    // Not shown: Implementations of GetValue() for all types used
    // with the following function
    
    func Example(v Packet) {
        // Call interface methods
    }
    

    Which method is best for you depends on exactly what you are doing. If most of your types are similar with small differences one or more common interfaces are probably best, if they are quite different then a type switch may be better. Whichever one produces the shortest, clearest code.

    Sometimes it is even best to use a mix of the two methods...

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

报告相同问题?

悬赏问题

  • ¥15 drone 推送镜像时候 purge: true 推送完毕后没有删除对应的镜像,手动拷贝到服务器执行结果正确在样才能让指令自动执行成功删除对应镜像,如何解决?
  • ¥15 求daily translation(DT)偏差订正方法的代码
  • ¥15 js调用html页面需要隐藏某个按钮
  • ¥15 ads仿真结果在圆图上是怎么读数的
  • ¥20 Cotex M3的调试和程序执行方式是什么样的?
  • ¥20 java项目连接sqlserver时报ssl相关错误
  • ¥15 一道python难题3
  • ¥15 牛顿斯科特系数表表示
  • ¥15 arduino 步进电机
  • ¥20 程序进入HardFault_Handler