For the first example, I always thought the "runtime.KeepAlive" call is essential before. But after reading the explanations from Bryan C. Mills on Slack, I changed my mind now.
Bryan C. Mills said: The GC tracks pointers through their original allocations — the pointer scan does not care about lexical types, only allocation types. On Tuesday, April 21, 2020 at 8:11:49 PM UTC-4, Ian Lance Taylor wrote: > > On Tue, Apr 21, 2020 at 6:49 AM T L <tapi...@gmail.com <javascript:>> > 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/83712696-b845-4db1-acdc-34b15b50baf4%40googlegroups.com.