How to use the command 'go run' (with examples)
The go run
command is used to compile and run Go code without saving a binary. It is a convenient way to quickly execute Go code without the need to compile and save a separate binary file.
Use case 1: Run a Go file
Code:
go run path/to/file.go
Motivation:
Running a Go file directly using go run
is useful when you want to quickly execute a specific Go file without the need to compile and save a separate binary file. This is particularly handy for small scripts or when you are still actively working on a Go file.
Explanation:
go run
: The command itself to compile and run the Go code.path/to/file.go
: The path to the Go file you want to execute. Replacepath/to/file.go
with the actual path to your Go file.
Example output:
If you have a Go file called hello.go
with the following code:
package main
import "fmt"
func main() {
fmt.Println("Hello, world!")
}
Running the command go run hello.go
will output:
Hello, world!
Use case 2: Run a main Go package
Code:
go run path/to/package
Motivation:
Using go run
on a main Go package allows you to compile and execute the entire package without needing to manually specify the entry point file. This is especially useful when working on larger projects with multiple Go files.
Explanation:
go run
: The command itself to compile and run the Go code.path/to/package
: The path to the main Go package you want to execute. Replacepath/to/package
with the actual path to your Go package.
Example output: Assuming you have a Go package with the following project structure:
myproject/
|- main.go
|- utils/
|- helper.go
If main.go
contains the following code:
package main
import "fmt"
import "myproject/utils"
func main() {
fmt.Println(utils.GetHello())
}
And utils/helper.go
contains the following code:
package utils
func GetHello() string {
return "Hello, world!"
}
Running the command go run myproject
will output:
Hello, world!
Conclusion:
The go run
command is a handy tool for quickly compiling and running Go code without the need to save a binary file. It provides flexibility for running both individual Go files and entire packages with ease. Whether you need to run a small script or test out a larger project, go run
is a valuable command in your Go toolkit.