Type func with Interface Parameter: Variance Error Explained
In Go, an attempt to invoke a function passed as an argument to another function expecting an interface{} type may result in a "cannot use a (type func(int)) as type myfunc in argument to b" error. This error arises due to the lack of variance support in Go interfaces.
Variance
Variance refers to the ability of a subtype to be used wherever its supertype is expected. In a covariant type system, subtypes can replace supertypes in both input and output positions. Contravariance, on the other hand, allows supertypes to replace subtypes in input positions.
Go Interfaces
Go interfaces do not exhibit variance. This means that while an int can be passed to a function expecting interface{}, the same is not true for func(int) and func(interface{}).
Understanding the Error
In the example provided, func(int)int does not implement func(interface{})int because:
Solution
To resolve the error, you could pass func(int) into a function expecting interface{}, as shown in the following code:
package main import "fmt" func foo(x interface{}) { fmt.Println("foo", x) } func add2(n int) int { return n + 2 } func main() { foo(add2) }
The above is the detailed content of Why Does Go Give a Variance Error When Using Functions with Interface Parameters?. For more information, please follow other related articles on the PHP Chinese website!