Type func with Interface Parameter Incompatibility Error
In Go, declaring a type function to accept any value conforming to interface{} appears straightforward. However, invoking a function passed as an argument that adheres to this type specification raises an error.
This error stems from the concept of type variance, particularly the lack of covariance in Go's interfaces. While an integer (int) can be passed to a function expecting interface{}, the same principle does not hold true for functions.
Specifically, func(int) and func(interface{}) are not compatible types. Even though int conforms to interface{}, func(int) does not conform to func(interface{}). This is because interfaces in Go are invariant.
To resolve this issue, consider passing func(int) to a function expecting interface{}, as demonstrated in the following example:
package main import "fmt" type myfunc interface{} func foo(x interface{}) { fmt.Println("foo", x) } func add2(n int) int { return n + 2 } func main() { foo(add2) }
In this example, func(int)int implements interface{}, thus avoiding the type incompatibility error.
The above is the detailed content of Why Doesn't Go Allow Passing `func(int)` to `func(interface{})` Despite `int` Satisfying `interface{}`?. For more information, please follow other related articles on the PHP Chinese website!