从其他包访问主要包

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

Access main package from other package

问题

我想从另一个包中访问主要包,但这是不可能的,因为主文件不在一个目录中。我已经尝试将主文件放在一个目录中,但当我尝试导入它时,我会得到以下错误:
import "../main" 是一个程序,而不是可导入的包

我之所以想要这样做,是因为我有一个TCP服务器和一个Web服务器需要一起工作。Web服务器可以通过主包获取TCP服务器,而TCP服务器可以通过主包获取Web服务器。

我已经让Web服务器和TCP服务器彼此读取(没有使用主包),但我想将应用程序的某些部分保持在一个地方。

我想要的这个东西是可能的吗(通过主包)?还是这样做很愚蠢?

英文:

I want to access the main package from another package, but this is impossible because the main file isn't in a directory. I already tried putting the main file in a directory, but when I try to import it I get this error:
import "../main" is a program, not an importable package

The reason that I want this because I have a tcp server and a webserver that work together. The webserver can get the tcp server via the main package and the tcp server can get the webserver via the main package.

I already got it working with the webserver and tcpserver reading from each other(without the main package in the middle), but I want to keep some parts of the application at one place.

Is the the thing I want possible(Via the main package)? Or is it just stupid.

答案1

得分: 106

你不能import主包。任何共享的代码应该放在一个单独的包中,可以被main(和其他包)导入。

英文:

You cannot import the main package. Any shared code should go in a separate package, which can be imported by main (and other packages).

答案2

得分: 0

另一种修复方法是从主函数中传递一个函数调用。在你的tcpwebserver中创建一个函数,接受一个函数值作为参数,然后在main函数中调用它。

因为golang main是一个程序,而不是可导入的package

英文:

Another way to fix this is to pass a function call from the main .
in which you create a function in your tcp or webserver then accepts a value in a function . then call it in the main

Because golang main is a program, not an importable package

huangapple
  • 本文由 发表于 2017年6月8日 03:02:54
  • 转载请务必保留本文链接:https://go.coder-hub.com/44420826.html
匿名

发表评论

匿名网友

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

确定