Skip to main content

Go Syntax

Every Go file is built from the same few parts:

  • A package declaration
  • Imported packages
  • Functions
  • Statements and expressions

The short program below contains all of them, so let's walk through it:

Example

Line 1: Go programs are organized into packages, and the package keyword says which one this file belongs to. Here, that is main.

Line 2: import ("fmt") brings in the files of the fmt package so we can use them.

Line 3: This line is empty. Go doesn't care about white space, but adding some makes your code easier to read.

Line 4: func main() {} defines a function. The code you put between its curly brackets {} is what gets executed.

Line 5: fmt.Println() comes from the fmt package and prints text. Here, the text it prints is "Hello World!".

Note: Executable Go code always belongs to the main package.

Prompt
Write a Go program that prints "Hello World!" to show basic Go syntax structure.
Output: Go program and captured output

Go Statements

The line fmt.Println("Hello World!") is an example of a statement.

Go separates statements in two ways: with a semicolon ";", or by ending the line with the Enter key.

Why does Enter work? Go quietly adds a ";" at the end of the line for you, even though you never see it in your source code.

This has one important consequence: a left curly bracket { is not allowed at the beginning of a line.

The program below breaks that rule. Look at the error it produces:

Example

Prompt
Show what happens when the opening curly bracket is placed on a new line in Go.
Output: Go program and captured output

Go Compact Code

Go will also accept very compact code like the program below. We don't recommend writing this way, though, because it is much harder to read:

Example

Prompt
Write a Go program on a single line using semicolons to separate statements.
Output: Go program and captured output