How to achieve zero memory copy conversion between golang string string and character array []byte

 1 minute to read

We usually use the following methods to achieve the conversion between string and character array:

a:="Hello World!"
var b = []byte(a)
fmt.Println(b)
c:=string(b)
fmt.Println(c)

Although this form is commonly used, memory copy will occur, which is not suitable for scenarios with high performance requirements.

How to achieve zero memory copy conversion between string and character array?

We can achieve this by manipulating pointers with unsafe.Pointer. The specific implementation is as follows:

import (
"fmt"
"reflect"
"unsafe"
)

func byte2string(b []byte) string {
return *(*string)(unsafe.Pointer(&b))
}

func string2byte(s string) (b []byte) {
bh := (*reflect.SliceHeader)(unsafe.Pointer(&b))
sh := (*reflect.StringHeader)(unsafe.Pointer(&s))
bh.Data = sh.Data
bh.Len = sh.Len
bh.Cap = sh.Len
return b
}

The first function implements []byte to string, and the second function implements string to []byte. The code implementation comes from the fasthttp framework.