Home > Backend Development > Golang > How Do I Run Multiple Go Files in the Same Package Using `go run`?

How Do I Run Multiple Go Files in the Same Package Using `go run`?

Linda Hamilton
Release: 2024-12-21 22:15:27
Original
224 people have browsed it

How Do I Run Multiple Go Files in the Same Package Using `go run`?

Separating Code into Multiple Files Within the Main Package for "go run"

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.

Execution with "go run *.go"

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.

Sample Code Structure

Consider the following directory structure and accompanying files:

ls foo

# output:
main.go
bar.go
Copy after login

File bar.go

// file bar.go
package main

import "fmt"

func Bar() {
  fmt.Println("Bar")
}
Copy after login

File main.go

// file main.go
package main

func main() {
  Bar()
}
Copy after login

Initial Error

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.

Resolution with "go run *.go"

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".

For Windows Environments (Update)

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template