Skip to content
Tutorials Center
My learning

Topics

Lesson 3 of 147 ยท Getting Started

Go Syntax

Learn the rules of Go syntax - the package clause, imports, declarations, automatic semicolons, brace placement, exported names, gofmt, and how to read compiler errors.

Go's syntax is small on purpose. Once you know how a file is laid out, how statements end, and how names are made public or private, you can read almost any Go program. This lesson covers those rules, and shows the most common compile errors beginners hit so you recognize them on sight.

The layout of a Go file

Every Go source file has the same three parts, always in this order:

  1. A package clause: package main.
  2. Zero or more imports.
  3. Declarations of constants, types, variables and functions, in any order.
Go The parts of a Go file

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

Outside functions, every statement must start with a keyword: package, import, const, var, type or func. That is why the short form x := 1 is not allowed at package level. Inside a function body you can use any statement.

Notice that the order of declarations does not matter. main can call shout even though shout is written first here, and it would work just as well the other way around. Go does not need forward declarations.

Imports

An import names a package by its path. Several imports are grouped in parentheses, one per line. The name you use in code is the last element of the path:

Go
import (
	"fmt"           // fmt.Println
	"math/rand/v2"  // rand.IntN (the last element after the version is "rand")
	str "strings"   // an alias: str.ToUpper
	_ "embed"       // imported only for its side effects
)
  • An alias (str "strings") renames the package in this file. It is useful when two packages share a name.
  • A blank import (_) loads a package only for its initialization side effects, for example registering a database driver. You will meet it in database/sql.
  • A dot import (. "fmt") pulls every name in without a prefix. It is allowed, but avoided in real code because it hides where names come from.

Standard library paths have no dot in their first element (fmt, net/http). Third-party paths start with a domain name, such as github.com/user/project.

Statements end without semicolons

Go's formal grammar does use semicolons to end statements, but you almost never write them. The compiler inserts one automatically at the end of a line when the last token on that line is:

  • an identifier, a number, a string or character literal,
  • one of the keywords break, continue, fallthrough or return,
  • one of ++, --, ), ] or }.

That rule is simple, but it has one important consequence: you cannot break a line anywhere you like. A line that ends with an operator or a comma is not finished, so the statement continues on the next line. A line that ends with an identifier or ) is a complete statement.

Go Continuing a statement over several lines

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

Lines that end in + or , continue. When a composite literal spreads over several lines, the last element needs a trailing comma, because without it the line would end in an identifier or string and a semicolon would be inserted before the closing brace. You can also put two statements on one line with an explicit ;, though gofmt code does not.

Braces go on the same line

Because of automatic semicolons, the opening brace { must be on the same line as the statement it belongs to. If you put it on the next line, the compiler inserts a semicolon after main() and the code breaks. This is the "Allman style" mistake that C and C# programmers make:

Go Brace on the wrong line (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

The compiler reports ./main.go:6:1: syntax error: unexpected semicolon or newline before {. The fix is to keep { at the end of the line. Braces are also mandatory for every if, for and switch body, even a one-line body. There is no brace-less form.

Declarations

Go has four kinds of top-level declarations plus the short form for local variables:

Go
const Pi = 3.14159          // constant
var name = "Gopher"         // variable
type Celsius float64        // new type
func double(n int) int {    // function
	return n * 2
}

func demo() {
	x := 42 // short variable declaration, functions only
	_ = x
}

Related declarations can be grouped with parentheses:

Go
const (
	Small = 1
	Large = 100
)

var (
	host = "localhost"
	port = 8080
)

Variables and types are explored in the next chapters, starting with Variables and Zero Values.

Identifier rules

An identifier is the name of a variable, function, type, constant, package, label or struct field. The rules are short:

  • It is made of letters, digits and the underscore _, and it must not start with a digit. "Letter" means any Unicode letter, so grรถรŸe and ๆ•ฐ้‡ are legal, although plain ASCII is the convention.
  • It is case sensitive: total, Total and TOTAL are three different names (and, as the next section shows, the case of the first letter also decides visibility).
  • It cannot be one of the 25 keywords (break, func, range, type, var...). Predeclared names such as len, string or true are not keywords and can technically be shadowed, but doing so is almost always a mistake.
  • The single underscore _ is the blank identifier. It is a write-only name that discards a value (Variables and Zero Values explains it).
Go Valid identifiers and case sensitivity

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

By convention Go names use MixedCaps (userCount, UserCount), never snake_case, and short names for short scopes (i, n, err).

Exported and unexported names

Go has no public or private keyword. Visibility is decided by the first letter of the name:

  • A name starting with an uppercase letter is exported: other packages can use it (fmt.Println, strings.ToUpper).
  • A name starting with a lowercase letter is unexported: it is visible only inside its own package.

This applies to functions, types, variables, constants, struct fields and methods alike. It is a compact rule that you can read at the call site: fmt.Println is public API, and a helper called parseLine is not.

Go Exported and unexported names

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

Here everything is in package main, so even balance is accessible. The distinction matters once code is split into packages, which Packages covers. Go's naming conventions prefer short names and no get prefix for getters, so the getter above is called Balance, not GetBalance.

gofmt: one style for everyone

Go ships with a formatter, gofmt, that rewrites code into the standard style: tabs for indentation, spaces for alignment, consistent spacing around operators. Nearly every editor runs it on save. Because it is automatic, Go code bases look the same everywhere and style debates never start.

Terminal
gofmt -l .      # list files that are not formatted
gofmt -w main.go  # rewrite a file in place
go fmt ./...    # same thing, through the go command

Details are in The go Command and Basic Tooling. In our editor, indent with real tab characters to match what gofmt would produce.

The compiler is strict

Go refuses to compile some things other languages merely warn about. Two rules surprise newcomers most.

Unused imports

Importing a package you do not use is an error:

Go Unused import (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

The message is ./main.go:5:2: "os" imported and not used. It gives the file, line 5, column 2 and the import path.

Unused variables

A local variable that is declared but never used is also an error:

Go Unused variable (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

You get ./main.go:6:2: declared and not used: count. Fix it by using the variable, deleting it, or, when you must keep a value you do not need, assigning it to the blank identifier: _ = count. These two rules keep Go code free of dead weight, and they also keep builds fast. Unused function parameters, constants and package-level variables are fine.

Reading compiler errors

All Go compile errors follow one shape: file:line:column: message. The compiler reports the first handful of errors (ten by default), so fix them from the top and compile again, because later errors are sometimes caused by earlier ones. The column counts bytes, and a tab counts as one.

A typical error and what to do about it:

  • undefined: x means a name does not exist in scope. Check spelling and capitalization (fmt.println is undefined because println is not exported).
  • missing return means a function with a result type has a path that ends without returning.
  • cannot use x (variable of type T) as U value in argument means a type mismatch, covered in Type Conversion and Inference.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Which line is a valid declaration at package level (outside any function)?

    Outside functions every statement must begin with a keyword. The short form := is only allowed inside functions.
  2. 2. Why does 'func main()' followed by '{' on the next line fail to compile?

    A line ending in a closing parenthesis gets an automatic semicolon, so the opening brace must stay on the same line.
  3. 3. Which of these names is exported from its package?

    Names starting with an uppercase letter are exported. Everything else is private to the package.
  4. 4. What happens if you import a package and never use it?

    Unused imports (and unused local variables) are compile errors in Go.
  5. 5. Why does a multi-line slice literal need a trailing comma after the last element?

    A line ending in a string or identifier gets an automatic semicolon, which is a syntax error inside a literal. The trailing comma prevents that.

Summary

  • A file has a package clause, then imports, then declarations in any order.
  • Top-level statements must start with package, import, const, var, type or func; := is for function bodies.
  • The compiler inserts semicolons at line ends, so { stays on the same line and multi-line lists need a trailing comma.
  • Uppercase names are exported, lowercase names are private to the package.
  • gofmt gives all Go code one style, with tabs for indentation.
  • Unused imports and unused local variables are compile errors; errors read file:line:column: message.

Next: Comments and Documentation shows how to explain your code and how comments become documentation.