I'm pretty sure new example is not valid Go code to begin with. You violate the rules on converting from uintptr to unsafe.Pointer. If you read the rules at https://pkg.go.dev/unsafe#Pointer, a unitptr can not *generally *be converted to an unsafe.Pointer. Since this code is not valid, the question is pretty much moot.
On Thursday, September 23, 2021 at 2:23:47 AM UTC-4 chole...@gmail.com wrote: > Thanks, I see. How about this one? I use a temp variable to store sh.Data, > sh/ds/data are all no longer mentioned at the point when unsafe.Slice is > called. Do I need to use runtime.KeepAlive? > > package main > > import ( > "fmt" > "reflect" > "runtime" > "unsafe" > ) > > var b []byte > > func f(data interface{}) { > switch ds := data.(type) { > case []int32: > sh := (*reflect.SliceHeader)(unsafe.Pointer(&ds)) > l := len(ds) > d := sh.Data > runtime.GC() > b = unsafe.Slice((*byte)(unsafe.Pointer(d)), l*4) > } > // runtime.KeepAlive(data) > } > > func main() { > f([]int32{1, 2}) > runtime.GC() > fmt.Println(b) > } > > 在2021年9月23日星期四 UTC+8 上午6:11:48<Ian Lance Taylor> 写道: > >> On Wed, Sep 22, 2021 at 1:22 AM Cholerae Hu <chole...@gmail.com> wrote: >> > >> > https://play.golang.org/p/WJTH-lUukeb >> > >> > Do I need to uncomment line 23? IMHO, variable data and ds will not be >> used after line 16, so they can be collected in runtime.GC. But running it >> with gccheckmark=1 and clobberfree=1 doesn't show any problems. >> > >> > Are there any documents about the details or behavior of liveness >> analysis? >> >> I don't see any reason why that program should need runtime.KeepAlive. >> >> The local variable sh will point to data (aka ds), so the object will >> stay alive. This is not different than p := &data. After that point, >> if data is no longer mentioned, then the variable data is no longer >> live, but the value that p points to will remain alive. >> >> 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/a230e4be-a162-4385-9aab-99dadc25d061n%40googlegroups.com.