Go syntax, types and functions

Packages, the small type system, zero values, and functions that return more than one value.

Packages, variables and types

A Go program is a set of packages. Execution starts in package main, at func main. Visibility is decided by capitalisation: Println is exported, helper is not.

package main

import (
    "fmt"
    "strings"
)

func main() {
    var name string = "Ada"     // explicit type
    count := 3                  // short declaration: type inferred
    var ratio float64 = 0.75

    fmt.Println(strings.ToUpper(name), count, ratio)
}
TypeZero valueNotes
string""Immutable UTF-8 byte sequence
boolfalse
int / int640int is 64-bit on most platforms
float640The default floating-point type
errornilAn interface; nil means no error
[]T, map[K]VnilNil slice is usable, nil map is not writable
*TnilPointer; nil dereference panics
💡
Zero values are usable, so Go needs no constructors. var buf bytes.Buffer is ready to write to, and a nil slice can be appended to. Design structs so the zero value is a sensible starting state.

Functions and multiple returns

package main

import (
    "errors"
    "fmt"
)

func divide(a, b float64) (float64, error) {
    if b == 0 {
        return 0, errors.New("divide by zero")
    }
    return a / b, nil
}

func sum(nums ...int) (total int) {   // named result, variadic input
    for _, n := range nums {
        total += n
    }
    return                            // bare return uses the named result
}

func main() {
    q, err := divide(10, 4)
    if err != nil {
        fmt.Println("error:", err)
        return
    }
    fmt.Println(q, sum(1, 2, 3))
}
  • := declares and assigns; = only assigns. := needs at least one new variable on the left of the list.
  • Multiple assignment makes swapping trivial: a, b = b, a, with no temporary variable.
  • Unused local variables and unused imports are compile errors, not warnings, so dead code cannot accumulate.
  • Functions are values: assign divide to a variable, store it in a map of handlers, or pass it as an argument.
  • Errors are ordinary values. The convention is to return error last and check it immediately.

FAQ

Why will my program not compile with 'declared and not used'?
Go treats unused local variables and imports as errors to keep code clean. Delete them, or assign to the blank identifier _ when you deliberately ignore a value.
When do I use var instead of :=?
var works at package level and can declare a variable without a value (getting the zero value). := works only inside a function, infers the type, and needs at least one new name.

Slices and maps Goroutines and channels

Last refreshed 2026-09-18.