HowtoGo
Home / Basics / Hello, World
Basics

Hello, World

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!")
}
Terminal
$ go run main.go
Hello, World!

2 What each line does

Every line is doing one job, and none of them are optional.

NameTypeWhat it is for
package mainclauseMarks this as a program to run, rather than a library to import.
import "fmt"clausePulls in the formatting package, which is where printing lives.
func main()funcWhere the program starts. It takes nothing and returns nothing.
fmt.PrintlnfuncWrites 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.

Terminal
$ 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/hello

5 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 yet
Result

A package clause, an import, and a main function. Every Go program you write starts from these three.