2016-07-18 06:14
浏览 106

是否可以将接口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 {

// 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(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.

图片转代码服务由CSDN问答提供 功能建议

我是golang的新手,我想实现类似于C ++重载的重载方法,并且我的代码看起来 像这样的东西:

  type someStruct struct {
 val int 
 some string 
type object interface {
 // someStruct实现对象接口
func(s * someStruct)toByte(){
 switch str:= overLoadedObj。(type){\  n case string:
 fmt.Println(“ string:”,str)
 case int:
 fmt.Println(“ int:”,str)
 case对象:// *它不在这里 全部* 
 fmt.Println(“ interface obj”,str)
func main(){
重载(“ hello”)
重载(someStruct {val  :5,有些:“ say”})


如何确保 谁实现了 object interface (对象接口)将属于 case object type?


  • 写回答
  • 好问题 提建议
  • 关注问题
  • 收藏
  • 邀请回答

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.

    解决 无用
    打赏 举报

相关推荐 更多相似问题