Function by parameter, generic parameter type

Guys, I’m struggling with a problem here, maybe someone could help. I have a previously defined function, which I need to execute that function inside another function, passed by parameter, one of the parameters of that function the type can change, example of what I’m trying to do in playground;

PS: I dont have access to doSomthingA and doSomthingB functions code, those functions are generated and the second parameter type arg2 change the type name.

Appreciate any kind of help.

You either need generics: The Gotip Playground

Or to pass a wrapper function instead of doSomethingA or doSomethingB directly, like this: Go Playground - The Go Programming Language

Or you need to use reflection which would probably be the slowest: Go Playground - The Go Programming Language

1 Like

I think the problem is the signature of functions doSomethingA and doSomethingB, i mean
you are using func(a string, b interface{}) and the signature are func doSomethingA(arg1 string, arg2 typeA) and doSomethingA(arg1 string, arg2 typeB)
You can use generics or reflection or simply just change the signature of both functions to arg2 interface{} and change the code in your functions to:

func doSomethingA(arg1 string, arg2 interface{}) {
  fmt.Printf("ARG 1: %s / ARG 2: %s\n", arg1, (arg2.(*typeA)).any)
}

func doSomethingB(arg1 string, arg2 interface{}) {
  fmt.Printf("ARG 1: %s / ARG 2: %s\n", arg1, (arg2.(*typeB)).any)
}

Check the result of the type assertion to avoid a panic.

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.