It should work to just set the finalizer on the first byte of an allocation. i.e.:
s := make([]byte, N) runtime.SetFinalizer(&s[0], func(b *byte) { ... }) Note that the spec of runtime.SetFinalizer doesn't actually guarantee that this will work. But I think in the current implementation it will. > The argument obj must be a pointer to an object allocated by calling new, by taking the address of a composite literal, or by taking the address of a local variable. The result of make isn't "an object created by calling new", but it it close. On Saturday, December 28, 2019 at 9:27:29 PM UTC-8, John wrote: > > Looking for a little insight on if it is possible to do something: > > Given this type: > > type Blah struct { > Payload []byte > } > > What I'm looking for is to kick off a finalizer when a slice and all other > slices backed by the same array get GC'd. > > In lieu of that, whenver the pointer to the array backing a slice get's > GC'd. I realize that in this case, the slice actually may stay around when > the array is GC'd because an append creates a new array on the slice. > > I don't think the first is possible, as you can't call SetFinalizer() on > non-pointer types. And I can't use any wrappers or pointers to []byte in > lieu of []byte for my use case. > > I figure there is a way to use: > > hdr := (*reflect.SliceHeader)(unsafe.Pointer(&b.Payload)) > > to set a finalizer on the underlying arrray. > > But I'm not sure exactly how to convert the hdr.Data into the specific > array type pointer to use in SetFinalizer(). It may not be possible. > > To save some time on a few questions: I'm aware of the flaws of > SetFinalizer(), just looking to see if this can actually be done. > > Thanks for any help. > -- 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/bc352725-aefb-4812-ad12-823ec10beb81%40googlegroups.com.