Last active
December 27, 2018 02:53
-
-
Save zhu327/70e9c588382b99a77cd2450a0afba797 to your computer and use it in GitHub Desktop.
string byte 转换, 不需要申请内存, 对于不可变的byte, 以及临时变量转换有用, 需要变的byte一定不要用
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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