简体   繁体   English

如何在GO中另一个包中的文件中使用主包中的函数?

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

Hi I want to call a method inside the main package, my project struct is like this: src: 嗨,我想在主程序包中调用一个方法,我的项目结构如下:src:

  • go files : package main 转到文件:包主
  • Postgres folder: Postgres文件夹:

    • go files: postgres package 转到文件:postgres程序包

now I want to call a method inside main package from the go files inside the postgres folder that is from postgres package. 现在我想从来自postgres包的postgres文件夹中的go文件中调用主包中的方法。 I tried to import "foo/src" then using src.Myfunction but I got an error: 我尝试使用src.Myfunction导入“ foo / src”,但出现错误:

import "foo/src" is a program, not an importable package

The package main is supposed to be used only to implement the binary/command specific code. 软件包main应该仅用于实现二进制/命令特定的代码。 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. 如果您需要main导入某些内容,则该代码可能不特定于该命令,因此它应该属于另一个包。 After you refactor the code, you can import it from the package main and from your other package which also requires it. 重构代码后,可以从包main和也需要它的其他包中导入它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM