go build vs go run

Avatar of Rakesh Mothukuri

Rakesh Mothukuri

| Reading Time : 2 minutes

Avatar of Rakesh Mothukuri Avatar of Rakesh Mothukuri Avatar of Rakesh Mothukuri Avatar of Rakesh Mothukuri

Example :

package main

import "fmt"

func main() {
	fmt.Println("Hello World")
}

 

go build main.go

Above program will be able to turn into an executable file that will always print out “Hello World”. If we want our program to run again, we don’t have to compile the program again, we simply run the executable file. Therefore, if we want fast code that users interact with, we’d compile a program once and use the executable file.

 

go run main.go

If we ever wanted to modify our program? compiling another executable file and then running that file would not be ideal. And imagine if we have to do that every single time just to check a small change or fix an error! 😱 Amazingly, there is another command comes handy which is go run command followed by the name of the Go program. The go run command combines both the compilation and execution of code. This allows to quickly check the output of updated code.go run will NOT create an executable file in our current folder.

Update 05/02/2020 :

Another amazing Go developer Pascal Dennerly shared his experience from his projects which is the time it takes execute program go run is same as running the executable admittedly they all fit in the L2 cache.

go build -o DirectoryPath

Go community is awesome. Another Go developer Peter Hellberg introduced me to another parameter -o followed by go build allows to output binary to a specified location