duanjianxi8439 2017-04-18 08:00
浏览 73
已采纳

使用go的struct指针作为接口

I want to pass struct method as function value. Why does compilation fail if function is required to return interface{} and it returns *struct? It perfectly works if I try to return *struct from function that is declared to return interface{} (wrapper func).

package main

func main() {
        println("hello")
        testInterface(wrapper)          // works
        instance := MyStruct{}
        testInterface(instance.works)   // works
        testInterface(instance.fails)   // fails: ./main.go:8: cannot use instance.fails (type func(int) *MyStruct) as type func(int) interface {} in argument to testInterface
}

func testInterface(f func() interface{}) {
        f()
        return
}

type MyStruct struct {
}

func (s *MyStruct) works() interface{} {
        return s
}

func (s *MyStruct) fails() *MyStruct {
        return s
}

func wrapper() interface{} {
        s := MyStruct{}
        return s.fails()

}

  • 写回答

1条回答 默认 最新

  • doujiacai4986 2017-04-18 08:15
    关注

    That's because it does not fit the assignability criterias

    A value x is assignable to a variable of type T ("x is assignable to T") in any of these cases:

    • x's type is identical to T.
    • x's type V and T have identical underlying types and at least one of V or T is not a named type.
    • T is an interface type and x implements T.
    • x is a bidirectional channel value, T is a channel type, x's type V and T have identical element types, and at least one of V or T is not a named type.
    • x is the predeclared identifier nil and T is a pointer, function, slice, map, channel, or interface type.
    • x is an untyped constant representable by a value of type T.

    So, this explains why testInterface(instance.fails) fails: because the instance.fails is not assignable to the f func() interface{}.

    Now the second question:

    It perfectly works if I try to return *struct from function that is declared to return interface{} (wrapper func).

    It works fine, because the value of the *struct type is assignable to the interface{} type because of:

    1. this rule of the assignability: "T is an interface type and x implements T."
    2. "A type implements any interface comprising any subset of its methods and may therefore implement several distinct interfaces. For instance, all types implement the empty interface:" (bold is mine)

    References:

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

报告相同问题?

悬赏问题

  • ¥15 关于#网络#的问题:网络是从楼上引一根网线下来,接了2台傻瓜交换机,也更换了ip还是不行
  • ¥15 资源泄露软件闪退怎么解决?
  • ¥15 各位佬,下面的问题怎么用python实现?
  • ¥15 CCF-CSP 2023 第三题 解压缩(50%)
  • ¥30 comfyui openpose报错
  • ¥20 Wpf Datarid单元格闪烁效果的实现
  • ¥15 图像分割、图像边缘提取
  • ¥15 sqlserver执行存储过程报错
  • ¥100 nuxt、uniapp、ruoyi-vue 相关发布问题
  • ¥15 浮窗和全屏应用同时存在,全屏应用输入法无法弹出