Created
April 29, 2022 21:57
-
-
Save zergon321/22a6a94ea76f8798533c3fb3c59aaed4 to your computer and use it in GitHub Desktop.
Struct to byte slice in Golang
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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