I get it. Thanks for all your responses! 在2021年9月23日星期四 UTC+8 下午8:36:11<peterGo> 写道:
> > Package runtime > https://pkg.go.dev/runtime > > Documentation > > func KeepAlive > <https://cs.opensource.google/go/go/+/go1.17.1:src/runtime/mfinal.go;l=473> > > Note: KeepAlive should only be used to prevent finalizers from running > prematurely. > > Peter > > 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/d75ae8ed-465e-48a9-ba05-c5fccb665251n%40googlegroups.com.