Type func with Interface Parameter Incompatible Error
Problem:
When invoking a function passed as an argument to a type func that takes values conforming to interface{}, an error is encountered. For instance, in the following code:
Explanation:
This error stems from Go's lack of support for variance in its type system. Variance refers to the flexibility in using subtypes and supertypes in parameter arguments. Go's interfaces, unlike other type systems, do not support variance.
In the given example, while an int can be passed to a function that accepts interface{}, this does not extend to func(int) being compatible with func(interface{}). This is because interfaces in Go are not covariant.
Solution:
As a workaround, functions can be passed to functions expecting interface{} by implementing interface{} through an anonymous function:
This approach leverages the fact that func(int)int does implement interface{}.
For further insights into variance in programming languages, consider exploring the Wikipedia article and the post linked below:
The above is the detailed content of Why Does Go's Type System Produce 'Incompatible Error' When Passing Functions with Interface Parameters?. For more information, please follow other related articles on the PHP Chinese website!