how can i use a function inside main package from a file in another package in GO?

huangapple go评论91阅读模式
英文:

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.

huangapple
  • 本文由 发表于 2016年9月15日 20:09:13
  • 转载请务必保留本文链接:https://go.coder-hub.com/39510683.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定