使用main.go在其他程序包中声明的结构 [英] use structure declared in main.go in other package

查看:35
本文介绍了使用main.go在其他程序包中声明的结构的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 main.go 中声明了一个结构,如下所示:

I have a structure declared in main.go as shown below:

type Organization struct {
    ID    string `json:"id"`
    Count int    `json:"count"` //node count
}

我有一个名为 configuration 的程序包,并具有如下功能:

I have a package named configuration and have a function like this:

func foo(org main.Organization) {

}

问题是我无法访问 main.Organization .有什么方法可以访问另一个包中 main.go 中声明的结构?

The issue is I am not able to access main.Organization. Is there any way to access struct declared in main.go in another package?

推荐答案

除非在极少数情况下,否则无法导入 package main .

It's not possible to import package main except in certain rare circumstances.

我在邮件列表上找到了这种解释去年.

I found this explanation on a mailing list dated back last year.

但是,可以在另一个主程序包中导入一个主程序包.总结一下:

However importing a main package in another main package works. To summarize:

1)支持在外部测试中导入主程序包
2)支持在主包中导入主包
3) 不支持在非主包中导入主包

1) importing a main package in a external test is supported
2) importing a main package in a main package is supported
3) importing a main package in a non main package is not supported

这对我来说似乎很合理,但是AFAIK并未对此进行记录.

This seems reasonable to me, however AFAIK it is not documented.

来自语言规范

通过将称为主包的单个 未导入 程序包与它导入的所有程序包可传递地链接起来,可以创建一个完整的程序.主程序包必须具有程序包名称main并声明一个不带任何参数且不返回值的main函数.

A complete program is created by linking a single, unimported package called the main package with all the packages it imports, transitively. The main package must have package name main and declare a function main that takes no arguments and returns no value.

(在两个引号中都强调我的意思)

(emphasis mine in both quotes)

这篇关于使用main.go在其他程序包中声明的结构的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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