Skip to the workspace
Pebellslearn by building
Introduction to Go  ›  Lesson

Hello World in Go

Hello World in Go 12 minA runnable Go program is a file in package main with a func main, and it may only import packages it actually uses.

golang / Hello World in Go

Explore each scene at your own pace.

01 · The rule

The rule

Hello World in Go

A runnable Go program is a file in package main with a func main, and it may only import packages it actually uses.

Follow package main, imports and the entry function into visible output.

Every Go program, from tally to Kubernetes, starts the same way. Once you can read the smallest program line by line, every other Go file looks familiar.

The rule

package main plus func main makes a program; import only what you use.

Save this as main.go inside the tally module:

package main

import "fmt"

func main() {
	fmt.Println("tally is ready")
}

Run it with go run . and it prints tally is ready.

  • package main: every Go file starts by naming its package. The special name main says "this builds an executable", not a library.
  • import "fmt": brings in the standard formatting package. Several imports go in a parenthesised block, one per line: import ( "fmt" "os" ) written over four lines.
  • func main(): the entry point. It takes no arguments and returns nothing. When main returns, the program ends. Command-line arguments come from os.Args instead.
  • fmt.Println: you call something from a package as package.Name. It starts with a capital letter because only capitalised names are visible outside their package.

Go is strict in a helpful way:

  • An unused import is a compile error, not a warning. So is an unused local variable.
  • The opening brace { must sit on the same line as func main(). Go inserts semicolons at line ends automatically, so a brace on the next line breaks the statement.
  • Indentation uses tabs, and go fmt fixes layout for you.

Notice what is missing, too: no class wrapping main, no semicolons at line ends, no return 0. A program that exits normally reports success to the operating system; to signal failure you call os.Exit(1), which tally will do when it cannot open a file.

Scene 1 of 5
Hover to wake the cannons. Drag to move, or use arrow keys when focused. Press Enter to fire a shot.