This is a creation in Article, where the information may have evolved or changed.
Original: http://studygolang.com/articles/2909
Most of the techniques in this article are correct, but the transformations between the structure and []byte:
third-structure and []byte Mutual transfer one day, you want to convert a simple structure into binary data to save, when you think of Encoding/gob and Encoding/json, do a performance test, you think the efficiency is possible higher? So you try again Encoding/binady, performance also can, but you still not satisfied. But where is the bottleneck? You realize that the most efficient way is to completely do not parse the data or produce data Ah! What do you do? It's time to use this black magic: type mystruct struct {A IntB int}var sizeofmystruct = Int (unsafe. Sizeof (mystruct{})) Func mystructtobytes (S *mystruct) []byte {var x reflect. Sliceheaderx.len = Sizeofmystructx.cap = Sizeofmystructx.data = UIntPtr (unsafe. Pointer (s)) return * (*[]byte) (unsafe. Pointer (&x))}func bytestomystruct (b []byte) *mystruct {return (*mystruct) (unsafe. Pointer (*reflect. Sliceheader) (unsafe. Pointer (&b)). Data,))}
When the structure in the original text to slice, the structure of the pointer to the []byte data field ([]byte is originally reflect.sliceheader structure, with unsafe.sizeof can see his length of 24, another structure of interface{} The length is 16, about 8 bytes to save the data pointer, 8 bytes of storage type, I guess,,,), this is OK, but the slice to the structure of the time, incredibly with &b (type *[]byte) This form, this &b is a slice of this structure is sliceheader of the pointer , which is managed by GC, how can it be converted into a struct as a pointer? Should use &b[0],&b[0] equivalent to B.data