恐慌:SetUint使用通过未导出字段获取的值

时间:2018-11-14 05:45:50

标签: arrays go

我要从字节缓冲区接收到的服务器复制struct。

缓冲区的格式为固定大小的字节,如下所示。

00000000  83 27 48 12 6c 00 00 00  01 02 00 00 01 01 00 02  |.'H.l...........|
00000010  10 01 d2 02 96 49 00 00  00 00 87 d6 12 00 00 00  |.....I..........|
00000020  00 00 01 00 00 00 00 00  00 00 00 00 00 00 00 00  |................|
00000030  00 02 01 02 3c 01 01 00  00 00 01 01 01 01 18 10  |....<...........|
00000040  2c 01 90 01 01 6c 07 03  c8 02 01 02 03 9c 0a 0b  |,....l..........|
00000050  0c 00 00 00 01 01 00 00  00 00 00 00 00 01 01 01  |................|
00000060  01 01 01 01 01 01 01 01  01 00 01 01 01 00 00 00  |................|

我的结构在下面。

type HeaderT struct {
    magicValue [8]byte
    bodyLength [4]byte
    bodyVersion [1]byte
    ...
}

我的实现在下面。

func onMessageReceived(client MQTT.Client, message MQTT.Message) {
    payload := message.Payload()
    fmt.Printf("Received message on topic: %s\nMessage: \n%s\n", message.Topic(), hex.Dump(payload))

    header := HeaderT {}
    err := binary.Read(bytes.NewBuffer(payload[:]), binary.LittleEndian, &header)  // <-- error occurred at this line
    ...
}

我的代码如下所示。

  

恐慌:reflect:reflect.Value.SetUint使用使用获取的值   未导出的字段

     

goroutine 38 [运行中]:reflect.flag.mustBeAssignable(0x1a8)           /usr/local/go/src/reflect/value.go:231 + 0x1ee Reflection.Value.SetUint(0x12540e0,0xc0001a2000,0x1a8,0x83)           /usr/local/go/src/reflect/value.go:1551 + 0x2f编码/二进制。(* decoder).value(0xc000148d88,0x12540e0,   0xc0001a2000、0x1a8)           /usr/local/go/src/encoding/binary/binary.go:548 + 0x7c6编码/二进制。(* decoder).value(0xc000148d88,0x125cfc0,   0xc0001a2000、0x1b1)           /usr/local/go/src/encoding/binary/binary.go:510 + 0x104编码/二进制。(* decoder).value(0xc000148d88,0x129fa00,   0xc0001a2000、0x199)           /usr/local/go/src/encoding/binary/binary.go:523 + 0x2c5编码/二进制.Read(0x12fcf80,0xc00018a150,0x1300c60,0x14d76d0,   0x1248040、0xc0001a2000、0x0、0x0)           /usr/local/go/src/encoding/binary/binary.go:248 + 0x342 main.onMessageReceived(0x13012a0,0xc000140000,0x1300c00,   0xc000192000)

1 个答案:

答案 0 :(得分:4)

问题在于HeaderT的所有字段都不是“公开”的。

请注意,所有字段均以小写字母开头-这意味着这些字段对于程序包外部的任何代码均不可访问。

来自spec

  

导出的标识符

     

可以导出一个标识符,以允许从另一个程序包访问它。如果同时满足以下条件,则导出标识符:

     
      
  • 标识符名称的第一个字符是Unicode大写字母(Unicode类“ Lu”);和
  •   
  • 标识符在程序包块中声明,或者它是字段名称或方法名称。
  •   
     

所有其他标识符都不会导出。

尝试通过大写名称来导出它们:

type HeaderT struct {
    MagicValue [8]byte
    BodyLength [4]byte
    BodyVersion [1]byte
    ...
}