Home > Backend Development > Golang > Why Doesn't Go Allow Passing `func(int)` to `func(interface{})` Despite `int` Satisfying `interface{}`?

Why Doesn't Go Allow Passing `func(int)` to `func(interface{})` Despite `int` Satisfying `interface{}`?

Barbara Streisand
Release: 2024-12-29 18:41:11
Original
605 people have browsed it

Why Doesn't Go Allow Passing `func(int)` to `func(interface{})` Despite `int` Satisfying `interface{}`?

Type func with Interface Parameter Incompatibility Error

In Go, declaring a type function to accept any value conforming to interface{} appears straightforward. However, invoking a function passed as an argument that adheres to this type specification raises an error.

This error stems from the concept of type variance, particularly the lack of covariance in Go's interfaces. While an integer (int) can be passed to a function expecting interface{}, the same principle does not hold true for functions.

Specifically, func(int) and func(interface{}) are not compatible types. Even though int conforms to interface{}, func(int) does not conform to func(interface{}). This is because interfaces in Go are invariant.

To resolve this issue, consider passing func(int) to a function expecting interface{}, as demonstrated in the following example:

package main

import "fmt"

type myfunc interface{}

func foo(x interface{}) {
    fmt.Println("foo", x)
}

func add2(n int) int {
    return n + 2
}

func main() {
    foo(add2)
}
Copy after login

In this example, func(int)int implements interface{}, thus avoiding the type incompatibility error.

The above is the detailed content of Why Doesn't Go Allow Passing `func(int)` to `func(interface{})` Despite `int` Satisfying `interface{}`?. 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