为什么其他“main”包中定义的函数无法识别?

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

Why the functions defined in other "main" packages are not recognised?

问题

我有两个文件 main.go 和 main2.go。在 main.go 中,我定义了 main() 函数,并调用了 main2.go 中的 somefunc()。问题是,当我运行 go run main.go 时,它显示 somefunc() 未定义。基本上它不会扫描包中的其他 main 函数。然而,如果我在 main.go 中声明了 somefunc(),它就可以工作,但当我运行 go test 时,它会说该函数已经重新声明。

问题:有没有办法告诉 go run 像 go test 一样编译/运行包中的所有文件(在这种情况下是 main.go 和 main1.go),而不仅仅是 main.go?

英文:

I have to files main.go and main2.go . In main.go I have the main() function defined along with a call somefunc() which is in main2.go. The issue is that when I run go run main.go it says that somefunc() is undefined. Basically it doesn't scan the other main functions from package. However if I declare this somefunc() in main.go it works but when I run go test it says the function is redeclared.

Question: Is there any way that I can tell to go run to behave like go test and compile/run all the files from the package(in this case both main.go and main1.go) not just main.go?

答案1

得分: 4

你必须将所有文件作为go run的参数包含进去。

go run main1.go main.go

或者

go *.go

除非在同一文件夹中有测试文件。

英文:

You must include all the files as argument of the go run.

go run main1.go main.go

or

go *.go

Unless there are test files in the same folder.

huangapple
  • 本文由 发表于 2015年2月18日 05:32:48
  • 转载请务必保留本文链接:https://go.coder-hub.com/28571477.html
匿名

发表评论

匿名网友

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

确定