Home > Backend Development > Golang > Why Does Go's Type System Produce 'Incompatible Error' When Passing Functions with Interface Parameters?

Why Does Go's Type System Produce 'Incompatible Error' When Passing Functions with Interface Parameters?

Linda Hamilton
Release: 2025-01-01 12:21:10
Original
491 people have browsed it

Why Does Go's Type System Produce

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:

  • [Variance (computer science)](https://en.wikipedia.org/wiki/Variance_(computer_science))
  • [Variance in Generic Programming](https://www.fluentcpp.com/2018/11/29/variance-in-generic-programming/)

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!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template