Home >Backend Development >Golang >Why Does Go Report an Error When Passing a Function with a Specific Parameter Type to a Function Accepting an Interface{} Parameter?

Why Does Go Report an Error When Passing a Function with a Specific Parameter Type to a Function Accepting an Interface{} Parameter?

DDD
DDDOriginal
2024-12-25 13:03:10429browse

Why Does Go Report an Error When Passing a Function with a Specific Parameter Type to a Function Accepting an Interface{} Parameter?

Type Func with Interface Parameter Incompatibility

When defining a function type that accepts any value conforming to an interface, it may be confusing to encounter an error upon invoking a function that appears to match that specification.

Consider the following example:

type myfunc func(x interface{})

func a(num int) {
    return
}

func b(f myfunc) {
    f(2)
    return
}

func main() {
    b(a) // error: cannot use a (type func(int)) as type myfunc in argument to b
    return
}

The error arises because interfaces in Go exhibit invariance, meaning that while an int can be passed to a function expecting an interface{}, the same is not true for func(int) and func(interface{}).

In Go, functions with compatible types must have identical parameter and return types. Since func(int) and func(interface{}) do not satisfy this requirement, Go perceives them as incompatible.

To resolve this issue, consider using the following approach:

package main

import "fmt"

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 is passed to a function expecting interface{}. This is permitted because func(int)int implements interface{} which requires it to have a single method with specified input and return types.

For a more detailed explanation of variance in Go, refer to the Wikipedia article on the subject and the blog post linked in the answer provided.

The above is the detailed content of Why Does Go Report an Error When Passing a Function with a Specific Parameter Type to a Function Accepting an Interface{} Parameter?. 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