0
0
GoHow-ToBeginner · 3 min read

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:

  • go is the Go tool command.
  • run tells Go to compile and run the program.
  • filename.go is 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 .go extension.
  • Trying to run a file without a package main and func 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:

CommandDescription
go run filename.goCompile and run the Go program immediately
go build filename.goCompile 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.