Convert between slices of different types

前端 未结 7 1026
南旧
南旧 2020-11-30 01:35

I get a byte slice ([]byte) from a UDP socket and want to treat it as an integer slice ([]int32) without changing the underlying array, and vice ve

7条回答
  •  误落风尘
    2020-11-30 02:19

    Perhaps it was not available when the earlier answers were given, but it would seem that the binary.Read method would be a better answer than "the right way" given above.

    This method allows you to read binary data from a reader directly into the value or buffer of your desired type. You can do this by creating a reader over your byte array buffer. Or, if you have control of the code that is giving you the byte array, you can replace it to read directly into your buffer without the need for the interim byte array.

    See https://golang.org/pkg/encoding/binary/#Read for the documentation and a nice little example.

提交回复
热议问题