Relative Content

Tag Archive for gogenericsinterface

How to a return generic type in go

I’m very new to go, still in the phase of learning and couldn’t find any answers matching to my issue, so please don’t downvote.
I have this generic interface which can be instantiated by two type parameters, which I have absolutely no problems making new maps with the types implementing this interface. I also I’m able to insert and index the keys, but I’m facing a problem while trying to return the values from the maps using a generic function. Please help me fix the GetGenericIfaceVal function mentioned below. The compiler complaints that it cannot return the type c as it is an IncompatibleAssign.

How to use a generic interface with generic methods in structs in go?

How would you define a method in an interface to be able to accommodate to accept a set of certain types of arguments based on some type related to the implementing struct? Take the below code as an example I would like to make the validate method to be generic, basically being able to accept the value argument to be only of one of the types – int, float64, string. But if I try to make use of generics here, then it simply won’t work.. because go requires you to instantiate the generic type parameter at the time of defining the struct field. On the contrary, I would want to instantiate the type parameter on the time of instantiating the Payload's map index, so that the field is able to store all the different implementations (IntValidation, FloatValidation, StrValidation). But both of these things together don’t seem to be feasible.
So what would be the way to achieve this? Do we need to refactor and think about this in a different way?