How to Run a Go Program: Simple Steps for Beginners
To run a Go program, save your code in a file with a
.go extension and use the command go run filename.go in your terminal. This compiles and executes the program immediately without creating a separate executable file.Syntax
The basic command to run a Go program is go run filename.go. Here:
gois the Go tool command.runtells Go to compile and run the program.filename.gois the name of your Go source file.
You can also run multiple files together by listing them all after go run.
bash
go run filename.go
Example
This example shows a simple Go program that prints "Hello, Go!" to the console. Save it as hello.go and run it with go run hello.go.
go
package main import "fmt" func main() { fmt.Println("Hello, Go!") }
Output
Hello, Go!
Common Pitfalls
Common mistakes when running Go programs include:
- Not saving the file with a
.goextension. - Trying to run a file without a
package mainandfunc main()entry point. - Running the command from the wrong directory where the file is not located.
Always ensure your file is saved correctly and you are in the right folder in your terminal.
go
// Wrong way: // File saved as example.txt package main func main() {} // Right way: // File saved as example.go package main func main() {}
Quick Reference
Here is a quick summary of commands to run Go programs:
| Command | Description |
|---|---|
| go run filename.go | Compile and run the Go program immediately |
| go build filename.go | Compile the program into an executable file |
| ./filename (Linux/macOS) or filename.exe (Windows) | Run the compiled executable |
Key Takeaways
Use
go run filename.go to quickly compile and run Go programs.Make sure your Go file has a
.go extension and contains package main with func main().Run the command from the directory where your Go file is saved.
Use
go build to create an executable if you want to run the program multiple times without recompiling.Check for typos in file names and commands to avoid errors.