dongmaxi6763 2019-02-18 10:13
浏览 84
已采纳

具有接口参数不兼容错误的Golang类型的func

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
}
  • 写回答

1条回答 默认 最新

  • dousui8263 2019-02-18 16:25
    关注

    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.

    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.

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

    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)
    }
    

    Because func(int)int does implement interface{}.


    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 机器学习能否像多层线性模型一样处理嵌套数据
  • ¥20 西门子S7-Graph,S7-300,梯形图
  • ¥50 用易语言http 访问不了网页
  • ¥50 safari浏览器fetch提交数据后数据丢失问题
  • ¥15 matlab不知道怎么改,求解答!!
  • ¥15 永磁直线电机的电流环pi调不出来
  • ¥15 用stata实现聚类的代码
  • ¥15 请问paddlehub能支持移动端开发吗?在Android studio上该如何部署?
  • ¥20 docker里部署springboot项目,访问不到扬声器
  • ¥15 netty整合springboot之后自动重连失效