Today's Question:  What does your personal desk look like?        GIVE A SHOUT

Run code with multiple files in the same main package in GoLang

  sonic0002        2021-05-15 10:20:10       20,232        0    

To run a GoLang program, there needs to be a main() function defined. In some cases when developing some demo program which has multiple files and just wanna put them in the same main package and this folder is not in GOPATH, how to run the program?

Let's say we have following folder structure where the main() function is defined in main.go.

If you just run below command, it would fail to start to run the program and gives some error if some struct is defined in other files and being used.

PS D:\Project\Go\sourcecode_updater\v2> go run main.go
# command-line-arguments
.\main.go:35:11: undefined: Pool
.\main.go:76:12: undefined: UpdateJob

There are a few ways to run the program successfully.

go run *.go

In some *nix operating systems including Linux and MacOS, can run go run *.go which will load all go files in the package and run the main().

But this command doesn't work on Windows as token expansion doesn't work in the windows command line.

PS D:\Project\Go\sourcecode_updater\v2> go run *.go
CreateFile *.go: The filename, directory name, or volume label syntax is incorrect.

go run .

Similar to above command, this command will also try to load all files in current folder and run the main() function and it can work on Windows as well.

PS D:\Project\Go\sourcecode_updater\v2> go run .
all workers started
2021/05/15 23:15:54 start fetching posts to process
2021/05/15 23:15:54 start to process batch 1

go build

GoLang provides a very convenient and quick way to generate a executable binary so that it can be ran easily as well with go build command. 

PS D:\Project\Go\sourcecode_updater\v2> go build -o main.exe
PS D:\Project\Go\sourcecode_updater\v2> ./main
all workers started
2021/05/15 23:17:29 start fetching posts to process
2021/05/15 23:17:29 start to process batch 1

This is the beauty of GoLang.

GOLANG  EXECUTABLE  MAIN PACKAGE  MULTIPLE FILE 

Share on Facebook  Share on Twitter  Share on Weibo  Share on Reddit 

  RELATED


  0 COMMENT


No comment for this article.