doukun8944 2014-09-19 20:17
浏览 17
已采纳

为什么这两个结构不相等?

I have a struct in go:

type header struct {
    dataLength    uint16
    optDataLength uint8
    packetType    uint8
}
type packet struct {
        syncByte  uint8
        header    *header
        headerCrc uint8
        data      []byte
        optData   []byte
        dataCrc   uint8
}

If i have created an Encode and Decode function for creating packages and for encoding them into binary. However why does those two instances.header differ?

&{syncByte:85 header:0xc2080004b8 headerCrc:112 data:[2] optData:[] dataCrc:14}
&{syncByte:85 header:0xc2080004f8 headerCrc:112 data:[2] optData:[] dataCrc:14}

If i run Println on those two header's i get:

&{dataLength:1 optDataLength:0 packetType:5}
&{dataLength:1 optDataLength:0 packetType:5}

which to mee seems equal. But why do they look like 0xc2080004f8 vs 0xc2080004b8 when i cannot see the difference when i check on packet.header directly?

  • 写回答

2条回答 默认 最新

  • douxi2670 2014-09-19 21:15
    关注

    They aren't equal because it's comparing the pointer not the value of the pointer. You have few options.

    1. Don't use pointers and you won't be able to use slices either in either structs, you can use fixed size arrays.
    2. Write your own func (p *packet) Equals(o *packet) bool and compare stuff yourself.
    3. use reflect.DeepEqual, this is by far the slowest / least efficient solution, I'd personally go with #2.

    Simple implementation of #2:

    func (h *header) Equal(o *header) bool {
        return h != nil && o != nil &&
            h.dataLength == o.dataLength &&
            h.optDataLength == o.optDataLength &&
            h.packetType == o.packetType
    }
    
    func (p *packet) Equal(o *packet) bool {
        return p != nil && o != nil &&
            p.header.Equal(o.header) &&
            p.syncByte == o.syncByte &&
            p.headerCrc == o.headerCrc &&
            p.dataCrc == o.dataCrc &&
            bytes.Equal(p.data, o.data) &&
            bytes.Equal(p.optData, o.optData)
    }
    

    <kbd>playground</kbd>

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥20 有人能用聚类分析帮我分析一下文本内容嘛
  • ¥15 请问Lammps做复合材料拉伸模拟,应力应变曲线问题
  • ¥30 python代码,帮调试
  • ¥15 #MATLAB仿真#车辆换道路径规划
  • ¥15 java 操作 elasticsearch 8.1 实现 索引的重建
  • ¥15 数据可视化Python
  • ¥15 要给毕业设计添加扫码登录的功能!!有偿
  • ¥15 kafka 分区副本增加会导致消息丢失或者不可用吗?
  • ¥15 微信公众号自制会员卡没有收款渠道啊
  • ¥100 Jenkins自动化部署—悬赏100元