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

English 简体中文 繁体中文 ภาษาไทย Tiếng Việt
Summary

When developing Go programs with multiple files within the same main package, directly running `go run main.go` will fail to resolve symbols defined in other source files. To successfully execute such a program, especially when not within the GOPATH, developers have a few effective methods. On *nix systems, `go run *.go` can load all necessary files, though this command is not functional on Windows due to shell expansion differences. A more universal solution is `go run .`, which correctly processes all Go files in the current directory across all operating systems. Alternatively, `go build` generates a standalone executable binary, offering a convenient way to run the program directly after compilation.

要執行 GoLang 程式,需要定義一個 main() 函數。在某些情況下,當開發一些有多個檔案的示範程式,並且只想將它們放在同一個 main 套件中,而此資料夾不在 GOPATH 中時,該如何執行程式?

假設我們有以下的資料夾結構,其中 main() 函數定義在 main.go 中。

如果您只執行以下命令,它將無法啟動執行程式,並且如果某些結構在其他檔案中定義並被使用,則會出現一些錯誤。

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

有幾種方法可以成功執行程式。

go run *.go

在某些 *nix 作業系統(包括 Linux 和 MacOS)中,可以執行 go run *.go,它將載入套件中的所有 go 檔案並執行 main()

但是此命令在 Windows 上不起作用,因為 token 擴展在 Windows 命令列中不起作用。

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

go run .

與上述命令類似,此命令也會嘗試載入目前資料夾中的所有檔案並執行 main() 函數,它也可以在 Windows 上運作。

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 提供了一種非常方便快捷的方式來產生可執行二進位檔案,以便可以使用 go build 命令輕鬆執行它。

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

這就是 GoLang 的美妙之處。

GOLANG EXECUTABLE MAIN PACKAGE MULTIPLE FILE

  RELATED

  COMMENTS

0

No comment for this article.