我想知道为什么函数不能使用同类型的函数?请参阅以下伪函数.
游乐场:http://play.golang.org/p/ZG1jU8H2ZJ
package main
type typex struct {
email string
id string
}
type typey struct {
email string
id string
}
func useType(t *typex) {
// do something
}
func main() {
x := &typex{
id: "somethng",
}
useType(x) // works
y := &typey{
id: "something",
}
useType(y) // doesn't work ??
}
Run Code Online (Sandbox Code Playgroud)
因为它们是分开的类型.
你所追求的是Go可以用来保证类型包含相同签名的接口.接口包含编译器可以检查传入类型的方法.
这是一个工作样本:http://play.golang.org/p/IsMHkiedml
Go不会根据你的称呼方式神奇地推断出类型.它只会在它可以保证调用站点的参数与输入接口的参数匹配时才会这样做.
至于为什么 - Y不是X所以它为什么会起作用?
如果它们真的相同,你可以通过将typey转换为typex来轻松克服这个问题:
useType((*typex)(y))
Run Code Online (Sandbox Code Playgroud)
但是,如果它们相同,为什么有两种类型呢?