Go language reading small notes from the Hudada about unsafe. Pointer's share.

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

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.