Skip to content

Instantly share code, notes, and snippets.

@zergon321
Created April 29, 2022 21:57
Show Gist options
  • Save zergon321/22a6a94ea76f8798533c3fb3c59aaed4 to your computer and use it in GitHub Desktop.
Save zergon321/22a6a94ea76f8798533c3fb3c59aaed4 to your computer and use it in GitHub Desktop.
Struct to byte slice in Golang
package main
import (
"fmt"
"unsafe"
)
type Movement struct {
Opcode int
X float64
Y float64
Z float64
}
const (
movementSize = int(unsafe.Sizeof(Movement{}))
)
func main() {
mv := Movement{
Opcode: 32,
X: 13.34,
Y: 20.36,
Z: 45.13,
}
packet := (*[movementSize]byte)(unsafe.Pointer(&mv))[:]
fmt.Println(mv)
fmt.Println(len(packet))
fmt.Println(packet)
newMv := *(*Movement)(unsafe.Pointer(&packet[0]))
fmt.Println(newMv)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment