Home >Backend Development >Golang >Why Does Go Give a Variance Error When Using Functions with Interface Parameters?

Why Does Go Give a Variance Error When Using Functions with Interface Parameters?

Patricia Arquette
Patricia ArquetteOriginal
2024-12-29 18:06:17240browse

Why Does Go Give a Variance Error When Using Functions with Interface Parameters?

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:

  • func(int) expects an int parameter, while func(interface{}) expects an interface{} parameter.
  • func(int) returns an int, while func(interface{}) can return any value that implements interface{}.

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!

Statement:
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