You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
package main
import "fmt"
func CallOneArg[T1 any](f func(T1), args []any) {
f(args[0].(T1))
}
func CallTwoArgs[T1, T2 any](f func(T1, T2), args []any) {
f(args[0].(T1), args[1].(T2))
}
func Caller[F any](f F, args []any) {
switch len(args) {
case 1:
CallOneArg(f, args) // type F of f does not match func(T1) (cannot infer T1)
case 2:
CallTwoArgs(f, args) // type F of f does not match func(T1, T2) (cannot infer T1 and T2)
}
}
func MyFunc1(arg1 string) {
fmt.Println(arg1)
}
func MyFunc2(arg1 string, arg2 string) {
fmt.Println(arg1, arg2)
}
func main() {
Caller(MyFunc1, []any{"Hello World!"})
Caller(MyFunc2, []any{"Hello World!", "Bye World!"})
}
What did you expect to see?
The program to compile because type F does match func(T1) in the first case, and func(T1, T2) in the second case.
If you explicitly type assert such as CallOneArg(any(f).(func(string)) and CallTwoArgs(any(f).(func(string, string)), args) it will compile, but that defeats the entire purpose of the code. I'm not sure if this is a bug or a case of type inference not being implemented but it makes sense for this to work.
What did you see instead?
./compile.go:16:15: type F of f does not match func(T1) (cannot infer T1)
./compile.go:18:16: type F of f does not match func(T1, T2) (cannot infer T1 and T2)
The text was updated successfully, but these errors were encountered:
I believe the compiler is correct, there is no set of type parameters you can explicitly pass to make the code compile as is. F any is not a sufficient constraint for it to be used as a function, F could be any other value
Unlike many projects, the Go project does not use GitHub Issues for general discussion or asking questions. GitHub Issues are used for tracking bugs and proposals only.
What version of Go are you using (
go version
)?Does this issue reproduce with the latest release?
What operating system and processor architecture are you using (
go env
)?go env
OutputWhat did you do?
What did you expect to see?
The program to compile because type F does match func(T1) in the first case, and func(T1, T2) in the second case.
If you explicitly type assert such as
CallOneArg(any(f).(func(string))
andCallTwoArgs(any(f).(func(string, string)), args)
it will compile, but that defeats the entire purpose of the code. I'm not sure if this is a bug or a case of type inference not being implemented but it makes sense for this to work.What did you see instead?
The text was updated successfully, but these errors were encountered: