Golang multiple files in main package

匿名 (未验证) 提交于 2019-12-03 01:18:02

问题:

I currently have a single file in my main package called main.go. How do I split the contents of main.go into multiple files without creating a separate package because the code isn't reusable.

I want a directory structure like this:

$ ls foo  main.go bar.go 

bar.go

package main  import "fmt"  func Bar() {     fmt.Println("Bar") } 

Then in main.go

package main  func main() {     Bar() } 

回答1:

The code above actually works. The problem was I needed to run

go run *.go 

instead of

go run main.go 


回答2:

As mentioned in "How to compile Go program consisting of multiple files?", go run expects a list of files, since it "compiles and runs the main package comprising the named Go source files".
So you certainly can split your main package in several files with go run.

That differs from go build/go install which expect package names (and not go filenames).
A simple go build would produce an executable named after the parent folder.

Note that, as illustrated by this thread, a go run *.go wouldn't work in a Windows CMD session, since the shell doesn't do wildcard expansion.



回答3:

For Windows install Cygwin and use it instead of command prompt. "go run *.go" will work then.



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!