On Tue, Apr 21, 2020 at 6:49 AM T L <tapir....@gmail.com> 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 > }
Since you are correctly using *reflect.StringHeader, it doesn't matter whether the stack is copied at that moment. You are pointing at the actual string value, so the pointer will be adjusted. As far as I can see, this is safe. (Of course, it's not safe if somebody modifies the contents of the returned []byte.) Ian -- 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/CAOyqgcXNOMpv%2ByKxR2O%2ByBYoSKxLQ-Ab5vt3y%2ByM2ADKRmqvbA%40mail.gmail.com.