And is the runtime.KeepAlive call in the following program essential to keep the correctness?
package main import ( "fmt" "unsafe" "reflect" "runtime" ) func main() { a := [6]byte{'G', 'o', 'o', 'g', 'l', 'e'} bs := []byte("Golang") hdr := (*reflect.SliceHeader)(unsafe.Pointer(&bs)) hdr.Data = uintptr(unsafe.Pointer(&a)) runtime.KeepAlive(&a) // Is this line essential here? hdr.Len = 2 hdr.Cap = len(a) fmt.Printf("%s\n", bs) // Go bs = bs[:cap(bs)] fmt.Printf("%s\n", bs) // Google } On Tuesday, April 21, 2020 at 9:48:08 AM UTC-4, T L wrote: > > func String2ByteSlice(str string) (bs []byte) { > strHdr := (*reflect.StringHeader)(unsafe.Pointer(&str)) > sliceHdr := (*reflect.SliceHeader)(unsafe.Pointer(&bs)) > > // Is it possible that the str value is allocated on stack > // and the stack grows at this moment, so the address value > // stored in strHdr.Data will become obsoleted? > > sliceHdr.Data = strHdr.Data > sliceHdr.Len = strHdr.Len > sliceHdr.Cap = strHdr.Len > > runtime.KeepAlive(&str) > > return > } > > -- You received this message because you are subscribed to the Google Groups "golang-nuts" group. To unsubscribe from this group and stop receiving emails from it, send an email to golang-nuts+unsubscr...@googlegroups.com. To view this discussion on the web visit https://groups.google.com/d/msgid/golang-nuts/483cb026-c8ab-41eb-9e3b-479a3e750d03%40googlegroups.com.