Go core
Browse topics

Variables, constants and shadowing

Version
1.27
Review
Draft

Summary#

A var declaration without a value starts at the type's zero value. := declares and initializes variables inside a function. An untyped constant can be assigned to a type that can represent its value. A declaration such as size := 50 uses the constant's default type, int.

Syntax#

go
var retries int
name := "worker"
const batchSize = 50

Example#

go
package main

import "fmt"

const batchSize = 50 // untyped

func main() {
	var retries int
	var label string
	var ready bool
	fmt.Printf("%d %q %t\n", retries, label, ready)

	// One constant, used as two different types.
	var ratio float64 = batchSize / 4.0
	var small int8 = batchSize
	fmt.Println(ratio, small)

	total := 10
	if total > 5 {
		total := total * 2 // a new variable in this block
		fmt.Println("inner", total)
	}
	fmt.Println("outer", total)

	status, total := "done", 30 // declares status, reuses total
	fmt.Println(status, total)
}

Expected output#

Text
0 "" false
12.5 50
inner 20
outer 10
done 30

Common mistakes#

Using := in a nested block declares a new variable that hides the outer one, as inner shows. Write = to update the existing variable. In the same block, := can reuse existing variables of the same type as long as it also declares at least one new non-blank name.

Version applicability#

The syntax and example work from Go 1.0.

Sources#

Attribution
DevLookup contributors
License
CC-BY-4.0