package GoString
import (
"reflect"
"testing"
"unsafe"
)
func TestEqual(t *testing.T) {
str := "hello world"
str1 := str[0:6]
t.Log(str == str1) // false
sh1 := (*reflect.StringHeader)(unsafe.Pointer(&str))
sh2 := (*reflect.StringHeader)(unsafe.Pointer(&str1))
t.Log(sh1 == sh2) // false
t.Log(sh1.Len == sh2.Len) // false
// ---------------------------------------------
t.Log(sh1.Data == sh2.Data) // true
// 要注意的是,string的切片共享底层数组的问题
sh2.Len = len(str1)
t.Log(*(*string)(unsafe.Pointer(&sh2.Data))) //hello world
}
func Clone(s string) string {
if len(s) == 0 {
return ""
}
b := make([]byte,len(s))
copy(b,s)
return *((*string)(unsafe.Pointer(&b))) // byte数组到string的零内存拷贝转换
}
Go 1.18 新增API strings.Clone()
最新推荐文章于 2024-05-28 09:50:38 发布