github.com/zhiqiangxu/util@v0.0.0-20230112053021-0a7aee056cd5/hack.go (about) 1 package util 2 3 import ( 4 "reflect" 5 "unsafe" 6 ) 7 8 // Slice does no copy to change string to slice 9 func Slice(s string) (b []byte) { 10 pbytes := (*reflect.SliceHeader)(unsafe.Pointer(&b)) 11 pstring := (*reflect.StringHeader)(unsafe.Pointer(&s)) 12 pbytes.Data = pstring.Data 13 pbytes.Len = pstring.Len 14 pbytes.Cap = pstring.Len 15 return 16 } 17 18 // String does no copy to change slice to string 19 // use your own risk 20 func String(b []byte) (s string) { 21 pbytes := (*reflect.SliceHeader)(unsafe.Pointer(&b)) 22 pstring := (*reflect.StringHeader)(unsafe.Pointer(&s)) 23 pstring.Data = pbytes.Data 24 pstring.Len = pbytes.Len 25 return 26 }