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
Release: 2024-12-29 18:06:17
Original
222 people have browsed it

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)
}
Copy after login

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!

source:php.cn
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