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...

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

报告相同问题?

悬赏问题

  • ¥30 python代码,帮调试
  • ¥15 #MATLAB仿真#车辆换道路径规划
  • ¥15 java 操作 elasticsearch 8.1 实现 索引的重建
  • ¥15 数据可视化Python
  • ¥15 要给毕业设计添加扫码登录的功能!!有偿
  • ¥15 kafka 分区副本增加会导致消息丢失或者不可用吗?
  • ¥15 微信公众号自制会员卡没有收款渠道啊
  • ¥100 Jenkins自动化部署—悬赏100元
  • ¥15 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条