Skip to content

Instantly share code, notes, and snippets.

@zhu327
Last active December 27, 2018 02:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save zhu327/70e9c588382b99a77cd2450a0afba797 to your computer and use it in GitHub Desktop.
Save zhu327/70e9c588382b99a77cd2450a0afba797 to your computer and use it in GitHub Desktop.
string byte 转换, 不需要申请内存, 对于不可变的byte, 以及临时变量转换有用, 需要变的byte一定不要用
package utils
import (
"reflect"
"unsafe"
)
func BytesToString(b []byte) string {
return *(*string)(unsafe.Pointer(&b))
}
func StringToBytes(s string) []byte {
sh := (*reflect.StringHeader)(unsafe.Pointer(&s))
bh := reflect.SliceHeader{sh.Data, sh.Len, 0}
return *(*[]byte)(unsafe.Pointer(&bh))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment