Saturday, April 19, 2025
HomeGolangReflecting on Weak Pointers: A Proposal for reflect-Primarily based Weak Pointer Creation...

Reflecting on Weak Pointers: A Proposal for reflect-Primarily based Weak Pointer Creation – Getting Assist


With the introduction of weak pointers in Go 1.24, I’ve been exploring their use instances. I’ve discovered a state of affairs the place I have to create and handle weak pointers dynamically, primarily based on varieties decided at runtime – primarily, I want reflection capabilities for weak pointers.

The present weak.Pointer is generic, and so far as I can inform, Go doesn’t presently help calling generic features by way of reflection. This makes it inconceivable to create a weak.Pointer[T] when T is barely often called a mirror.Sort.

I’ve appeared via the difficulty tracker and the golang-nuts mailing record, and I haven’t discovered any current discussions instantly addressing this. Earlier than I submit a proper proposal on GitHub, I needed to gauge the neighborhood’s opinion on whether or not including reflection help for weak pointers could be a helpful addition to the language.

Right here’s a tough sketch of what I envision the API may appear to be (utilizing a hypothetical weak.PointerAny):
package deal weak // or maybe a brand new package deal like mirror/weak

sort PointerAny struct {
	typ mirror.Sort
	u   unsafe.Pointer
}

func MakeAny(ptr any) PointerAny {
	ptr = abi.Escape(ptr)
	v := mirror.ValueOf(ptr)
	t := v.Sort()
	if t.Type() != mirror.Pointer {
		panic("ptr isn't a pointer")
	}
	var u unsafe.Pointer
	if ptr != nil {
		u = runtime_registerWeakPointer(v.UnsafePointer())
	}
	runtime.KeepAlive(ptr)
	return PointerAny{typ: t.Elem(), u: u}
}

func (p PointerAny) Worth() any {
	if p.u == nil {
		return nil
	}
	ptr := runtime_makeStrongFromWeak(p.u)
	if ptr == nil {
		return nil
	}
	return mirror.NewAt(p.typ, ptr).Interface()
}

This PointerAny would enable making a weak pointer from an any (which have to be a pointer) and retrieving the unique worth as an any.

Is there a compelling cause to not add this? Would including reflection help for weak pointers introduce important complexity or have unintended penalties? Maybe there are elementary the explanation why this hasn’t been applied already.

I’m keen to listen to your ideas. Thanks!

IMHO, weak pointer doesn’t have to know the precise sort of the worth. Mirror is all the time very pricey and I doubt it’s a typical use. You may all the time merely add your personal wrapper round weak pointer with its sort:

sort MyPointer struct {
    t mirror.Sort
    p weak.Pointer
}

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments