英文:
why you can't use a type from a different package if it has the same 'signature' ? golang
问题
我想知道为什么函数在相同类型的情况下不起作用?请看下面的伪函数。
Playground: 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) // 正常工作
y := &typey{
id: "something",
}
useType(y) // 为什么不工作??
}
英文:
I'm wondering why the functions are not working with types of the same kind ? See the following pseudo functions.
Playground: 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 ??
}
答案1
得分: 8
因为它们是不同的类型。
你想要的是一个接口,Go可以使用它来确保类型包含相同的签名。接口包含编译器可以检查传入的类型的方法。
这里有一个可工作的示例:http://play.golang.org/p/IsMHkiedml
Go不会根据你的调用方式自动推断类型。只有在可以确保调用点的参数与输入接口的参数匹配时,它才会这样做。
英文:
Because they are separate types.
What you're after is an interface that Go can use to guarantee that the types contain the same signatures. Interfaces contain methods that the compiler can check against the types being passed in.
Here is a working sample: http://play.golang.org/p/IsMHkiedml
Go won't magically infer the type based on how you call it. It will only do this when it can guarantee that the argument at the call site matches that of the input interface.
答案2
得分: 8
关于为什么 - Y不是X,所以为什么它会起作用?
如果它们确实是相同的,你可以通过将typey转换为typex来轻松解决这个问题:
useType((*typex)(y))
然而,如果它们是相同的,为什么要有两种类型呢?
英文:
As to the why - Y is not X so why would it work?
You can easily overcome this, if they really are identical, by casting typey into typex:
useType((*typex)(y))
However, if they are identical, why have 2 types?
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论