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

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?

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

playground

Each call to Decode allocates a new value of type header. You are observing the different addresses for these allocated headers. The two headers values have the same contents, but they are at different addresses.