英文:
how can i use a function inside main package from a file in another package in GO?
问题
你好,我想调用主包中的一个方法,我的项目结构如下:
src:
- go文件:主包
- Postgres文件夹:
- go文件:postgres包
现在我想从postgres包中的go文件中调用主包中的一个方法。
我尝试导入"foo/src",然后使用src.Myfunction,但是我得到了一个错误:
import "foo/src"是一个程序,而不是可导入的包。
英文:
Hi I want to call a method inside the main package, my project struct is like this:
src:
-
go files : package main
-
Postgres folder:
- go files: postgres package
now I want to call a method inside main package from the go files inside the postgres folder that is from postgres package.
I tried to import "foo/src"
then using src.Myfunction but I got an error:
import "foo/src" is a program, not an importable package
答案1
得分: 3
main
包应该只用于实现二进制/命令特定的代码。它通常从其他包中导入代码,将所有内容粘合在一起。如果你需要从main
包中导入某些内容,那么该代码可能与该命令无关,因此应该属于另一个包。在重构代码之后,你可以从main
包和其他需要它的包中导入它。
英文:
The package main
is supposed to be used only to implement the binary/command specific code. It usually imports code from other packages to glue everything together. If you need to import something from the package main
, that code is probably not specific to that command, so it should belong to another package. After you refactor the code, you can import it from the package main
and from your other package which also requires it.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论