TTuck

Variables are declared explicitly and the compiler checks their types, for example that a function receives arguments of the right kind.

package main

import (
	"fmt"
	"strconv"
)

func main() {

var declares one or more variables.

	var a = "initial"
	fmt.Println(a)

You can declare several at once.

	var b, c int = 1, 2
	fmt.Println(b, c)

Go infers the type of an initialized variable.

	var d = true
	fmt.Println(d)

A variable declared without a value gets its zero value: 0 for numbers, "" for strings, false for booleans, and nil for pointers, slices, and maps.

	var e int
	var f string
	var g []int
	fmt.Println(e, f == "", g == nil)

Inside a function, := is shorthand for declaring and initializing a variable.

	h := "apple"
	fmt.Println(h)

Variables can be reassigned, and several can be assigned at once, which makes swapping easy.

	x, y := 1, 2
	x, y = y, x
	fmt.Println(x, y)

The blank identifier _ discards a value you do not need.

	_, second := 10, 20
	fmt.Println(second)

An unused local variable is a compile error, which keeps code tidy:

	// unused := 3
	// error: declared and not used: unused

:= may redeclare names already in this block when at least one name is new. count already exists, err does not, so count is reused and err is created.

	count := 1
	count, err := strconv.Atoi("8")
	fmt.Println("redeclared:", count, err)

The same spelling in a new block creates new variables and hides the outer ones. The outer err is still nil. This is the usual err := bug.

	{
		count, err := strconv.Atoi("no")
		fmt.Println("inner:", count, err)
	}
	fmt.Println("outer err:", err)
}
$ go run ./03_variables
initial
1 2
true
0 true true
apple
2 1
20
redeclared: 8 <nil>
inner: 0 strconv.Atoi: parsing "no": invalid syntax
outer err: <nil>