Go programs need to be turned into machine code before they can run. This process is called compilation. Understanding how Go compiles and runs helps you write and run your programs smoothly.
0
0
Go compilation and execution flow
Introduction
When you want to turn your Go code into a program that your computer can run.
When you need to check if your Go code has errors before running it.
When you want to create a fast, standalone program from your Go code.
When you want to understand what happens behind the scenes when you run 'go run' or 'go build'.
Syntax
Go
go build [options] [packages] go run [options] [files]
go build compiles your code into an executable file.
go run compiles and runs your code in one step without creating a separate executable file.
Examples
This command compiles the file
main.go into an executable file named main (or main.exe on Windows).Go
go build main.go
This command compiles and runs
main.go immediately without saving an executable file.Go
go run main.go
This command compiles all Go files in the current directory and all subdirectories.
Go
go build ./...
Sample Program
This simple Go program prints a message. You can compile it with go build and run the executable, or run it directly with go run.
Go
package main import "fmt" func main() { fmt.Println("Hello, Go compilation and execution!") }
OutputSuccess
Important Notes
When you use go run, Go compiles your code to a temporary executable, runs it, then deletes the executable.
go build creates a permanent executable you can run anytime without recompiling.
Compilation checks your code for errors before creating the executable.
Summary
Go code must be compiled before it runs.
go build creates an executable file.
go run compiles and runs code in one step without saving an executable.