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 组策略中的计算机配置策略无法下发
  • ¥15 如何绘制动力学系统的相图
  • ¥15 对接wps接口实现获取元数据
  • ¥20 给自己本科IT专业毕业的妹m找个实习工作
  • ¥15 用友U8:向一个无法连接的网络尝试了一个套接字操作,如何解决?
  • ¥30 我的代码按理说完成了模型的搭建、训练、验证测试等工作(标签-网络|关键词-变化检测)
  • ¥50 mac mini外接显示器 画质字体模糊
  • ¥15 TLS1.2协议通信解密
  • ¥40 图书信息管理系统程序编写
  • ¥20 Qcustomplot缩小曲线形状问题