douzhang8840 2016-07-18 06:14
浏览 183
已采纳

是否可以将接口obj传递给interface {}类型?

I'm new to golang and I want to implement an overloaded method something similar to C++ overloading, and my code looks something like this:

type someStruct struct {
    val  int
    some string
}

type object interface {
    toByte()
}

// someStruct implementing an object interface
func (s *someStruct) toByte() {
}

func overload(overLoadedObj interface{}) {

    switch str := overLoadedObj .(type) {
    case string:
        fmt.Println("string : ", str)
    case int:
        fmt.Println("int : ", str)
    case object: //* It doesn't come here at all*
        fmt.Println("interface obj", str)
    }
}

func main() {
    overload("hello")
    overload(5)
    overload(someStruct{val: 5, some: "say"})
}

So the question is:

How to make sure that whoever implements object interface will fall in at case object type ?

Thanks in advance.

  • 写回答

1条回答 默认 最新

  • dongyunqin7307 2016-07-18 06:29
    关注

    The "problem" is that someStruct.toByte() has a pointer receiver. This means the method toByte() belongs to the type *someStruct and not to someStruct. So someStruct does not implement object, only *someStruct. And you pass a value of someStruct to overload().

    Pass a value of *someStruct, and you'll get what you want:

    overload(&someStruct{val: 5, some: "say"})
    

    Output (try it on the Go Playground):

    string :  hello
    int :  5
    interface obj &{5 say}
    

    Relevant section from the spec: Method sets:

    A type may have a method set associated with it. The method set of an interface type is its interface. The method set of any other type T consists of all methods declared with receiver type T. The method set of the corresponding pointer type *T is the set of all methods declared with receiver *T or T (that is, it also contains the method set of T).

    Behind the scenes

    Note that behind the scenes when you call overload() like this:

    overload(&someStruct{val: 5, some: "say"})
    

    This will wrap the *someStruct pointer value in an interface{} value (because overload() has a parameter of interface{} type), and not in an interface value of type object.

    Inside overload(), the type switch will check types in the listed order. And when it reaches case object, it will see that the value wrapped in the overLoadedObj parameter does implement object so this case will be executed.

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

报告相同问题?

悬赏问题

  • ¥15 程序不包含适用于入口点的静态Main方法
  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记