dushaoshuai / dushaoshuai.github.io

https://www.shuai.host
0 stars 0 forks source link

Go: string 和 []byte 相互转化 #120

Open dushaoshuai opened 1 year ago

dushaoshuai commented 1 year ago

safe

func BytesToString(b []byte) string {
    return string(b)
}

func StringToBytes(s string) []byte {
    return []byte(s)
}

unsafe

unsafe 1

// StringToBytes converts string to byte slice without a memory allocation.
func StringToBytes(s string) []byte {
    return *(*[]byte)(unsafe.Pointer(
        &struct {
            string
            Cap int
        }{s, len(s)},
    ))
}

// BytesToString converts byte slice to string without a memory allocation.
func BytesToString(b []byte) string {
    return *(*string)(unsafe.Pointer(&b))
}

unsafe 2

// StringToBytes converts string to byte slice without a memory allocation.
// For more details, see https://github.com/golang/go/issues/53003#issuecomment-1140276077.
func StringToBytes(s string) []byte {
    return unsafe.Slice(unsafe.StringData(s), len(s))
}

// BytesToString converts byte slice to string without a memory allocation.
// For more details, see https://github.com/golang/go/issues/53003#issuecomment-1140276077.
func BytesToString(b []byte) string {
    return unsafe.String(unsafe.SliceData(b), len(b))
}

参见