如果它具有相同的“签名”,为什么不能使用不同包中的类型? golang [英] why you can't use a type from a different package if it has the same 'signature' ? golang

查看:83
本文介绍了如果它具有相同的“签名”,为什么不能使用不同包中的类型? golang的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道为什么这些函数不适用于相同类型的类型?请参阅以下伪功能。

游乐场: http://play.golang。 org / p / ZG1jU8H2ZJ

  package main 

type typex struct {
电子邮件字符串
id字符串
}

类型typey结构{
电子邮件字符串
id字符串
}

func useType(t * typex){
//做某事
}

func main(){
x:=& typex {
id :somethng,
}
useType(x)//作品
$ b $作者:=& typey {
id:something,
}
useType(y)//不起作用?


解决方案

因为它们是不同的类型。

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



下面是一个工作示例:http://play.golang.org/p/IsMHkiedml



Go不会基于你的方式神奇地推断出这种类型叫它。它只会在确保调用站点的参数与输入接口的参数匹配时才会这样做。


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 ??
}

解决方案

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.

这篇关于如果它具有相同的“签名”,为什么不能使用不同包中的类型? golang的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆