简体   繁体   中英

golang: trying to use `any` to match different functions

Given this function:

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

Unfortunately the func s 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).

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)

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) {}

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

maybe something like this could work

Apply[K any]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2025 STACKOOM.COM