The smallest Go program that does something: a package clause, one import, and a main function that prints a line.
Your first Go program
1 Put this in a file called main.go
Make a folder to hold it. What you see is a complete Go program: it compiles as it stands, and running it prints a line.
package main
import "fmt"
func main() {
fmt.Println("Hello, World!")
}$ go run main.go
Hello, World!2 What each line does
Every line is doing one job, and none of them are optional.
| Name | Type | What it is for |
|---|---|---|
| package main | clause | Marks this as a program to run, rather than a library to import. |
| import "fmt" | clause | Pulls in the formatting package, which is where printing lives. |
| func main() | func | Where the program starts. It takes nothing and returns nothing. |
| fmt.Println | func | Writes its arguments and a newline to the terminal. |
3 Run it, or build a binary
go run compiles into a temporary folder, runs the result, and throws it away. go build leaves a real binary you can move to another machine.
The binary has no runtime to install alongside it. Everything it needs is inside the file.
$ go run main.go
Hello, World!
$ go build -o hello .
$ ./hello
Hello, World!4 Create a module
A single file runs on its own. The moment you add a second package or pull in someone else's code, Go wants a go.mod to keep track of it.
mkdir hello
cd hello
go mod init example.com/hello5 Print with Println, Printf, or Sprintf
Println adds spaces and a newline. Printf takes a format string and adds nothing. Sprintf hands the text back instead of printing it.
name := "World"
fmt.Println("Hello,", name) // Hello, World
fmt.Printf("Hello, %s!\n", name) // Hello, World!
msg := fmt.Sprintf("Hello, %s!", name) // nothing printed yetA package clause, an import, and a main function. Every Go program you write starts from these three.