douyonglang4845 2014-06-24 10:06
浏览 9

为什么您不能使用具有相同“签名”的其他程序包中的类型? golang

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 ??
}
  • 写回答

2条回答 默认 最新

  • douliang9057 2014-06-24 10:19
    关注

    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.

    评论

报告相同问题?

悬赏问题

  • ¥15 stm32开发clion时遇到的编译问题
  • ¥15 lna设计 源简并电感型共源放大器
  • ¥15 如何用Labview在myRIO上做LCD显示?(语言-开发语言)
  • ¥15 Vue3地图和异步函数使用
  • ¥15 C++ yoloV5改写遇到的问题
  • ¥20 win11修改中文用户名路径
  • ¥15 win2012磁盘空间不足,c盘正常,d盘无法写入
  • ¥15 用土力学知识进行土坡稳定性分析与挡土墙设计
  • ¥70 PlayWright在Java上连接CDP关联本地Chrome启动失败,貌似是Windows端口转发问题
  • ¥15 帮我写一个c++工程