by wara23arish · 4y ago · 0 comments
have a function take in an array of T
T is generic with type constraint call Constraint
problem is calling that function wont work because it has to instantiated with one of the types found in the Constraint which beats the whole purpose. I need this to pass in structs that belong to Constraint.
I tried a multitude of different things and nothing seemed to work.
I ended up reading the Go library for how it handles SPrintF args and did something similar with a type switch and reflection wizardry.
Im still a junior programmer so it could be that I just didnt know how or I underestimate the solution for this.
But I figured once we have a type Constraint defined with a function, it should be relatively simple to not have to instantiate it with ONE concrete type and allow the Constraint types as args.
if anyone knows a better way to do this please let me know
If that's correct, then is this what you need? https://go.dev/play/p/_e-Uipgo5OQ It seems quite straightforward so I think I'm missing some context, but this can be a start.
I made an example of what Im trying to do. One thing I didnt specify is the function used is a receiver function. For some reason this means the type had to be instantiated on the receiver itself Spotter in this case. https://goplay.tools/snippet/Vj7uVMi0mWn Basically have two different types that implement an interface, pass them into a receiver function in a composite type (array,slice). Part of the issue is that you cant have the receiver function without defining instantiating the type on the receiver Spotter in this case.
https://go.googlesource.com/proposal/+/refs/heads/master/des...
I believe the most simple fix would be to have a separate function which is generic that takes in the struct along with the slice of T with the constraints that apply to it.
Hopefully someone can bridge that gap for you.
https://goplay.tools/snippet/Vj7uVMi0mWn
Basically have two different types that implement an interface, pass them into a receiver function in a composite type (array,slice).
Part of the issue is that you cant have the receiver function without defining instantiating the type on the receiver Spotter in this case.