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

在包括 Linux 和 MacOS 在内的一些 *nix 操作系统中,可以运行 go run *.go,它将加载包中的所有 go 文件并运行 main()

但是此命令在 Windows 上不起作用,因为令牌扩展在 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.