DEFINITIVE GUIDE
go run vs go build vs go install
Have you ever thought what's the difference between go build, go run and go install? Three almost similar go commands.
Go has three variations of similar commands go run, go build, and go install. We will see in this story what is the purpose of each command and how to use them.
Each of these commands either takes a single Go file or a list of Go files. Here in this story, we will use a Go hello world program for example to refer along the way.
// file name : hello.go
package mainimport "fmt"func main(){
fmt.Println("Hello, world!")}
go run
If you run the command go run hello.go
in your terminal/command prompt you should see the output as Hello, world!
printed.
What happens when you run this command is Go compiles the code into a binary file, But places this file in a temporary directory and executes this binary file from there, and deletes it after your program finishes. This command is useful for testing small programs during the initial development stage of your application.
go build
So now you want to you have the binary you built for the application to use later or run this binary on a remote computer then you need to use go build
command as below which creates a binary file named hello
in the current directory(hello.exe in windows)
go build hello.go
Tip: If you want to change the name of the binary that generated use a file -o
// This results a binary file "application"
go build -o application hello.go
go install
This command does perform the exact operation as go build
but places the binary in $GOPATH/bin` directory alongside the binaries of third-party tools installed via go get
now if you run $GOPATH/bin/hello
you will see Hello, world!
printed on your terminal.
Suggestion when using go install
is to use this if you are planning to write tools that you want to use on your own computer or usego build
if you are to run this application in elsewhere