Home > Mobile >  golang: trying to use `any` to match different functions
golang: trying to use `any` to match different functions

Time:08-17

Given this function:

func Apply(label string, func(msg any, arg any) (any, error) {
...
}

Unfortunately the funcs I need to pass to Apply don't match in their signature.

//Func 1
func GetAddress(prompt string, custom Param) (string, error) {}

// Func 2
func GetIdentifier(prompt string) (utils.ID, error) {}

But why does the compiler (go1.18) complain if I try

Apply(label, GetAddress)

with

[compiler IncompatibleAssign] [E] cannot use GetAddress (value of type func(prompt string, custom Param) (string, error)) as func(msg any, arg any) (any, error) value in argument to Apply

Why does msg any not match to prompt string, custom Param not to arg any and the string type in the return not to the any type in the return?

What exactly is incompatible here? (Ignore if you think the design is bad for a sec, I just want to understand that first).

CodePudding user response:

Change the func declaration to use type parameters

func Apply[T1 any, T2 any, T3 any](label string, func(msg T1, arg T2) (T3, error)

Now to call it

Apply[string, Param, string](label, GetAddress)

When the function has type parameters, you may be able to drop the type parameter list with the compiler automatically inferring what the variant types are:

Apply(label, GetAddress)

CodePudding user response:

The reason why the code you wrote doesn't actually work is that the types have to match exactly in the go language. The interface type is valid for incoming value types, the definition types must be the same in function, however, if the definition type is interface (or "any"), the parameter value can be any. (string|int ...)

func Apply(label string, func(msg any, arg any) (any, error) {
...
}

//Func 1
func GetAddress(prompt any, custom any) (any, error) {}
// Func 2
func GetIdentifier(prompt any) (any, error) {}

CodePudding user response:

func Apply[K any](label string, func(msg K, arg K) (K, error) { ... }

maybe something like this could work

Apply[K any]

  • Related