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)
}| Type | Zero value | Notes |
|---|---|---|
string | "" | Immutable UTF-8 byte sequence |
bool | false | |
int / int64 | 0 | int is 64-bit on most platforms |
float64 | 0 | The default floating-point type |
error | nil | An interface; nil means no error |
[]T, map[K]V | nil | Nil slice is usable, nil map is not writable |
*T | nil | Pointer; 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
divideto a variable, store it in a map of handlers, or pass it as an argument. - Errors are ordinary values. The convention is to return
errorlast 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.Related
Slices and maps Goroutines and channels
Last refreshed 2026-09-18.