Bug fixes in go language black magic

Source: Internet
Author: User
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

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.