如果它具有相同的"签名",为什么你不能使用来自不同包的类型?golang

use*_*073 4 go

我想知道为什么函数不能使用同类型的函数?请参阅以下伪函数.

游乐场: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)

Sim*_*ead 7

因为它们是分开的类型.

你所追求的是Go可以用来保证类型包含相同签名的接口.接口包含编译器可以检查传入类型的方法.

这是一个工作样本:http://play.golang.org/p/IsMHkiedml

Go不会根据你的称呼方式神奇地推断出类型.它只会在它可以保证调用站点的参数与输入接口的参数匹配时才会这样做.


Not*_*fer 6

至于为什么 - Y不是X所以它为什么会起作用?

如果它们真的相同,你可以通过将typey转换为typex来轻松克服这个问题:

useType((*typex)(y))
Run Code Online (Sandbox Code Playgroud)

但是,如果它们相同,为什么有两种类型呢?

  • @SimonWhitehead,这是因为typex和typey具有相同的底层类型,因此,可以进行转换.实际上,Not_a_Golfer在这里做的是等于定义:`type typex struct {email,id string}; type typey typex;`参见http://play.golang.org/p/I5yayfmRYJ (5认同)