键入func且接口参数不兼容错误 [英] Type func with interface parameter incompatible error

查看:84
本文介绍了键入func且接口参数不兼容错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经声明了一个新类型func,该类型可以采用任何符合interface{}的值.但是,当我调用已作为参数传递的函数(符合该类型规范)时,会出现错误.

I have declared a new type func that takes any value that conforms to interface{}. However, when I invoke a function that has been passed as an argument (conforming to that type specification) I get an error.

有人可以解释为什么会这样吗?下面是最简单的示例,可以用来重现该问题.

Can somebody explain why this is the case? Below is the simplest example I could recreate the issue with.

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
}

推荐答案

此处要查找的概念是 方差 .某些类型系统和类型支持协方差 contravariance ,但是Go的接口不支持.

The concept you're looking for here is variance in the type system. Some type systems and types support covariance and contravariance, but Go's interfaces do not.

虽然int可以传递给期望interface{}的函数,但对于func(int)func(interface{})却不能这么说,因为接口的行为不协变.

While an int can be passed to a function that expects interface{}, the same cannot be said about func(int) and func(interface{}), because interfaces do not behave covariantly.

如果类型x实现了接口ii,则并不意味着func(x)实现了func(ii).

If type x implements interface ii, it doesn't mean that func(x) implements func(ii).

您可以做的是将func(int)传递到需要interface{}的函数中,这样您就可以做到

What you could do is pass func(int) into a function that expects interface{}, so you could do

package main

import "fmt"

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

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

func main() {
    foo(add2)
}

因为func(int)int 确实实现了interface{}.

除了答案顶部的Wikipedia链接外,这篇文章提供了有关各种差异编程语言支持的更多详细信息.它主要使用其他语言,因为方差最好用支持继承的语言来证明.

In addition to the Wikipedia link at the top of the answer, this post provides more details about the different kinds of variance programming languages support. It mostly uses other languages, because variance is best demonstrated with languages that support inheritance.

这篇关于键入func且接口参数不兼容错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆