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

Is it possible to pass interface obj to interface{} type?

我是 golang 的新手,我想实现一个类似于 C++ 重载的重载方法,我的代码如下所示:

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

所以问题是:

如何确保实现对象接口的人会落入案例对象类型?

提前致谢。

"problem"就是someStruct.toByte()有一个指针接收器。这意味着方法 toByte() 属于类型 *someStruct 而不是 someStruct。所以someStruct没有实现object,只有*someStruct。然后你将 someStruct 的值传递给 overload().

传递一个值*someStruct,你会得到你想要的:

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

输出(在 Go Playground 上尝试):

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

规范中的相关部分: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).

幕后花絮

请注意,当您像这样调用 overload() 时在幕后:

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

这会将 *someStruct 指针值包装在 interface{} 值中(因为 overload() 有一个 interface{} 类型的参数),而不是在接口值中输入 object.

overload() 中,type switch 将按照列出的顺序检查类型。当它到达 case object 时,它会看到包装在 overLoadedObj 参数中的值确实实现了 object,因此将执行这种情况。