This is a creation in Article, where the information may have evolved or changed.
First-get slice and string of memory data
Func Stringpointer (S string) unsafe. Pointer {p: = (*reflect. Stringheader) (unsafe. Pointer (&s)) return unsafe. Pointer (P.data)}func bytepointer (b []byte) unsafe. Pointer {p: = (*reflect. Sliceheader) (unsafe. Pointer (&b)) return unsafe. Pointer (P.data)}
Second type-turn []byte] into string
Package Testimport "Testing" import "unsafe" func test_bytestring (t *testing. T) {var x = []byte ("Hello world!") var y = * (*string) (unsafe. Pointer (&x)) var z = string (x) if Y! = z {t.fail ()}}func benchmark_normal (b *testing. B) {var x = []byte ("Hello world!") For I: = 0; i < B.N; i + + {_ = string (x)}}func benchmark_bytestring (b *testing). B) {var x = []byte ("Hello world!") For I: = 0; i < B.N; i + + {_ = * (*string) (unsafe. Pointer (&x))}}
This experiment proves that we can use []byte's data to make a string to go. Then two sets of benchmark are tested, respectively, to test the efficiency of the common type conversion and the forgery of string.
Passbenchmark_normal 20000000 63.4 ns/opbenchmark_bytestring 2000000000 0.55 Ns/opok GITHUB.COM/IDADA/GO-LABS/LABS28 2.486s
The third type-the structure and the []byte Mutual transfer
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,))}
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.