go run vs go build – Go command-line tools

go run vs go build go commands

In this blog, we will take learn the differences between go run vs go build command-line tools.

The Go Language comes with go command-line tools that help us to execute certain operations on the code or program using the command line interface.

Before go run vs go build, let’s take a look at both the commands individually.

Go Build

The go build command-line tool takes a .go file and generates an executable file for windows and binary files for Linux.

Note:- Go build tool will only make an executable or binary file if the .go file contains the main package and main function in it. The Program with the main package and main function is considered as a command and program without is considered as a package.

I am using a windows machine and bash terminal for executing the commands.

go build example

$go build main.go

The go build main.go will generate an executable file (Windows machine) from the name of the command file (eg. main.exe).

$ ls
main.exe  main.go

build and run go code

After getting an executable, we need to run it to get the output from the main.go file.

$ ./main.exe 
Hello World
Go run vs go build
Go build

Go Clean

The executable or binary file generated using go build command-line tool, can be deleted manually but the go tools have a command that helps us to delete the executable or binary file.

Go clean command is used to keep the folder free of previous builds.

$ go clean

After the go clean command. The Executable gets deleted and just the go file is remaining.

$ ls
main.go
go clean
Go clean

Go Run

Go Build tool has 3 steps, mainly

  • Building executable or binary files
  • Running the executable or binary files
  • Deleting the executable or binary files

This soon becomes a rigorous work when you are changing your code frequently and have to build and run the executable.

The Go tools have another command i.e go run that helps us to generate the executable/binary files, run it, and then delete it automatically, and we just get the output from the go file.

$ go run main.go
Hello World

After running go run command, when we do ls to list the files in the directory, no extra files are seen.

$ ls
main.go
go run vs go build
Go run

go run vs go build

If you want to keep your directory clean use go run command and if you want to use the executable file use go build command.

Hope you like it!

Also, read Why Golang is called the future of Server-side language?

Learn more about Go run vs Go Build from the official Documentation.

Learn Golang Basics:

Learn Golang Advanced Topics:

Tags: , ,

Leave a Reply

Your email address will not be published. Required fields are marked *