go不运行的文件不在主包中
我有一个非常简单的GO项目设置。 在root目录我有go.mod
文件和main.go
和一个称为main2
的文件夹。内部main2
文件夹中有main2.go
文件。
/
|_ go.mod
|_ main.go
|_ main2
|_ main2.go
从根目录中,我试图运行go run命令
go run main2/main2.go
,并引发错误:
软件包命令行 - arguments不是主要软件包
有人可以提供帮助吗?
I have a very simple Go project setup.
At root directory I have go.mod
file and main.go
and a folder called main2
. Inside main2
folder there is main2.go
file.
/
|_ go.mod
|_ main.go
|_ main2
|_ main2.go
From root directory I am trying to run go run command
go run main2/main2.go
and it throws error:
package command-line-arguments is not a main package
Can someone help?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您的main2.go文件的包必须为 main 。当有一个主包和项目中的函数主题时,编译器知道它将被编译为可执行文件,而不是库。
因此,请尝试将 package command-line-arguments 更改为 package main 在main2/main2.go文件中。
The package of your main2.go file must be main. When there is a main package, and a function main in your project, the compiler knows it will be compiled as a executable, and not as a library.
So try to change package command-line-arguments to package main inside the main2/main2.go file.
想象一下,golang可执行的是一所房子,里面只有一个前门和许多不同的房间。一旦您进入房屋,您就可以穿过任何想要的门,但是要进入室内,您必须先穿过前门。前门是主()功能。
Golang进入可执行文件的切入点是通过main()。如果要为单个可执行文件运行不同的逻辑路径,则可以使用命令行参数将main()用作路由函数到其他软件包:
然后,您可以使用以下内容运行程序:
go go run main.go option1
来自 Golang文档:
Imagine a golang executable as a house with only a front door and many different rooms inside it. You can go through any door you want once you are in the house, but to get inside you have to go through the front door first. That front door is the main() function.
Golang's entry point into an executable is through main(). If you want to run different logic paths for a single executable, you can use main() as a routing function to the other packages using command line arguments:
Then you can run your program with something like:
go run main.go option1
From golang documentation: