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条)

报告相同问题?

悬赏问题

  • ¥15 有偿求码,CNN+LSTM实现单通道脑电信号EEG的睡眠分期评估
  • ¥15 没有证书,nginx怎么反向代理到只能接受https的公网网站
  • ¥50 成都蓉城足球俱乐部小程序抢票
  • ¥15 yolov7训练自己的数据集
  • ¥15 esp8266与51单片机连接问题(标签-单片机|关键词-串口)(相关搜索:51单片机|单片机|测试代码)
  • ¥15 电力市场出清matlab yalmip kkt 双层优化问题
  • ¥30 ros小车路径规划实现不了,如何解决?(操作系统-ubuntu)
  • ¥20 matlab yalmip kkt 双层优化问题
  • ¥15 如何在3D高斯飞溅的渲染的场景中获得一个可控的旋转物体
  • ¥88 实在没有想法,需要个思路