英文:
How to call function in Go file from command line
问题
我有两个go文件:
main.go
otherFile.go
在'main.go'文件中,我有一个'main'函数,可以通过命令行调用它,像这样:
go run main.go
到目前为止都很好。
在'otherFile.go'文件中,我不能再有一个'main'函数,所以我有一个名为'otherFunction'的函数。
我该如何从命令行中调用'otherFile.go'中的这个函数,类似于我之前通过'go run main.go'调用'main.go'的方式?
我不一定希望运行main.go,也不希望通过导入等方式从main.go中调用'otherFunction'。
这种方式可行吗?还是我对此的理解有误?我是Go的新手,仍在努力理解一些基本概念。
谢谢。
英文:
I have 2 go files:
main.go
otherFile.go
Inside of 'main.go' I have a 'main' function and I can call it from the command line like this:
go run main.go
So far so good.
Inside of 'otherFile' I can't have another 'main' function so I have a function called 'otherFunction'.
How can I call this function in 'otherFile.go' from the command line, similarly to how I did 'go run main.go'?
I don't necessarily want main.go to run, or call 'otherFunction' from 'main.go' by importing it, etc.
Is this possible or am I thinking about it in the wrong way? I am new to Go so still trying to figure out some of the basic concepts.
Thanks.
答案1
得分: 2
你应该能够按照以下结构来组织你的项目,以实现你想要的效果:
/path/to/project/root/apps/an-app/main.go
another-app/main.go
package1/package2/package3/- . . .
其中,apps/an-app和apps/another-app是你想要运行的命令,而package1、package2和package3是被这些应用程序导入的共享包。
英文:
You should be able to do what you want, if you structure your project along these lines:
/path/to/project/root/apps/an-app/main.go
another-app/main.go
package1/package2/package3/- . . .
where apps/an-app and apps/another-app are your commands that you want to run, and package1, package2, and package3 are shared packages that are imported by the apps.
答案2
得分: 0
在otherFile.go中定义一个不同的package名称,例如:
package otherFile
添加main()函数,然后在该main()函数内运行你想要的函数。
从终端中,你可以运行go run otherFile.go。
Go语言的包系统与其他语言不同。但是如果你继续使用它们,你会理解的。
英文:
in the otherFile.go define a different package name. like:
package otherFile
Add the main() func, then run the function you want inside that main() func.
From the terminal, you run go run otherFile.go.
The package system is different from what other languages have. But you'll get the idea if you keep using them.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论