In the pursuit of developing reusable code, it is often beneficial to separate sections of the main program into distinct files while maintaining a cohesive package structure. However, encountering an error when running "go run main.go" can indicate a need to adjust the execution command.
To effectively run multiple files within the main package, modify the command from "go run main.go" to "go run *.go". This command instructs the compiler to process all Go files (with the ".go" extension) in the current directory, effectively combining the code from the individual files.
Consider the following directory structure and accompanying files:
ls foo # output: main.go bar.go
// file bar.go package main import "fmt" func Bar() { fmt.Println("Bar") }
// file main.go package main func main() { Bar() }
Attempting to run "go run main.go" with the above code structure would result in an error, reporting that "Bar" is undefined. This is because "go run main.go" only compiles and executes the "main.go" file.
By using "go run *.go", both "main.go" and "bar.go" are processed, allowing the main function in "main.go" to access the "Bar" function from "bar.go".
As of July 26th, 2019, for versions of Go >=1.11, the command "go run ." can be used on Windows machines to achieve the same result as "go run *.go".
The above is the detailed content of How Do I Run Multiple Go Files in the Same Package Using `go run`?. For more information, please follow other related articles on the PHP Chinese website!