Skip to content
Tutorials Center
My learning

Topics

Lesson 8 of 147 ยท Variables and Types

Variables and Zero Values

Learn Go variables - var and :=, multiple assignment, the blank identifier, zero values for every type, redeclaration and scope, with runnable examples.

A variable is a named place in memory that holds a value of one particular type. Almost every program you write will create variables to remember a user's name, count how many items are in a cart, or keep a running total. Go gives you two ways to declare them, and a very useful promise: a variable is never left uninitialized. If you don't give it a value, Go fills it with a well-defined default called its zero value.

This lesson covers the var keyword, the short declaration :=, declaring several variables at once, the blank identifier _, zero values for every kind of type, and the rules about scope and redeclaration that trip up newcomers. The next lessons build on it: constants, basic types and type conversion.

Declaring variables with var

The long form uses the var keyword, then the name, then the type, and optionally an initial value:

Go Declaring variables with var

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 type comes after the name. That feels backwards if you know C or Java, but it makes complicated declarations readable from left to right. var age int = 36 reads as "variable age of type int, starting at 36".

You can leave out the type when there is an initial value. Go works out the type from the value, which is called type inference:

Go
var city = "Lisbon"   // string
var count = 12        // int
var ratio = 0.75      // float64

Or you can leave out the value and keep the type. The variable then holds the zero value for that type (more on that below):

Go
var total int         // 0
var title string      // "" (the empty string)

You must provide at least one of the two. var x on its own is a syntax error, because Go would have no way to know what x is.

Short declarations with :=

Inside a function, you can use the short variable declaration :=. It declares a variable and assigns it in one step, and it infers the type:

Go The short declaration operator

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.

This is by far the most common form in real Go code. Use := whenever you are inside a function and have a starting value. Use var when you want the zero value, when you want to pick a specific type (such as var ratio float32 = 0.5), or when you are declaring something outside a function.

:= only works inside functions. At the top level of a file (package level), every declaration must start with a keyword, so you write var limit = 100 there, never limit := 100.

Giving a literal a specific type

Inference picks default types: int for whole-number literals, float64 for fractional ones, string, bool, and rune for character literals like 'x'. If you need a different type, either use var with the type or convert the value:

Go Choosing a type instead of the default

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.

Go never converts between these types for you, which is why type conversion gets its own lesson.

Declaring several variables at once

You can declare and assign several variables on one line:

Go
var x, y int = 1, 2
a, b := "left", "right"

When you have a block of related variables, group them in parentheses. This is common at package level:

Go Grouped declarations and multiple assignment

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 swap line x, y = y, x works without a temporary variable because Go evaluates all the right-hand expressions before it assigns anything. This is a feature you will use constantly, for example when reversing a slice or advancing two indexes in one step.

Functions can also return several values, and you capture them the same way: value, err := doSomething(). Multiple return values are a big topic of their own.

Zero values

Here is one of Go's best design choices. In C, reading a local variable you never set gives you garbage. In Go, every variable starts as its type's zero value:

Type Zero value
bool false
numbers (int, float64, ...) 0
string "" (empty string)
pointers, slices, maps, channels, functions, interfaces nil
arrays and structs every element or field set to its own zero value

See it for yourself:

Go The zero value of every kind of type

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 empty string prints as nothing at all, which is why the example uses %q (it shows the quotes). A nil slice is perfectly usable: it has length 0 and you can append to it. A nil map is only safe to read; writing to it panics, as you will see in maps.

Make the zero value useful

Go programmers lean on zero values to avoid boilerplate. You don't need a constructor to set a counter to 0, and many types in the standard library work straight from their zero value. For example a strings.Builder or a sync.Mutex is ready to use as soon as you declare it:

Go Zero values that are ready to use

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.

When you design your own types, try to make the zero value meaningful in the same way. You will see this advice again in the lessons on structs and new and make.

Assignment versus redeclaration

= assigns to a variable that already exists. := creates new variables. There is one special rule: in a := with several names on the left, at least one must be new. The ones that already exist (in the same scope) are simply assigned.

Go At least one new variable on the left of :=

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.

This rule is what makes the usual value, err := ... chain work in a function: after the first line, err is reused each time and only the new result variables are declared.

The rule has a sharp edge, though: if the only thing you wanted was to assign, writing := in a new scope creates a brand-new variable that shadows the outer one:

Go Shadowing with :=

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.

Shadowing is legal, but it causes real bugs, especially with err. The go vet tool and many editors can warn about it. If a variable changes value unexpectedly, look for a stray := inside an if or for block.

Unused variables are errors

Go refuses to compile a function that declares a local variable and never uses it. This keeps code clean and catches typos:

Go An 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.

The compiler stops with:

TEXT
./main.go:7:2: declared and not used: unused

The line and column point at the variable's name. Remove it, or use it. (This rule applies to local variables; package-level variables and function parameters may stay unused.)

The blank identifier

Sometimes you receive a value you really don't need, such as the index from a loop, or the error from a call you have decided to ignore. Assign it to the blank identifier _ and Go discards it:

Go Discarding values with the blank identifier

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.

_ is not a real variable: you can't read from it, and you can assign to it any number of times. The last line is an idiom you will meet in larger code bases: assigning to _ to make the compiler verify that a type implements an interface, without keeping any variable around. Don't worry about it yet; interfaces will explain it.

Ignoring an error with _ hides failures. Use it only when you are sure the call can't fail, or when you have a good reason to move on. Otherwise handle the error, as the error handling lessons show.

Package-level variables and scope

A variable declared outside any function belongs to the package: every function in the package can use it. A variable declared inside a function or block is visible only from its declaration to the end of that block.

Go
package main

import "fmt"

var counter = 0 // package-level: visible everywhere in the package

func increment() {
	counter++ // uses the package-level variable
}

func main() {
	increment()
	increment()
	fmt.Println(counter) // 2
}

Package-level variables are fine for configuration and for state that really is shared, but they make code harder to test and reason about, and they are not safe to change from several goroutines at once. Prefer passing values as function parameters when you can.

Names that start with an uppercase letter are exported (visible to other packages), and lowercase names are private to the package. Variable names are usually short and in camelCase: i, err, userCount. Use short names for short scopes and descriptive names for longer ones.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What is the value of n after var n int?

    Go always initializes variables. The zero value of every numeric type is 0.
  2. 2. Which line is a compile error at package level (outside any function)?

    The short declaration := is only allowed inside functions. Package-level declarations must begin with a keyword such as var.
  3. 3. What does this print? a, b := 1, 2; a, b = b, a; fmt.Println(a, b)

    All right-hand expressions are evaluated before any assignment, so this swaps the two values without a temporary variable.
  4. 4. What does this print? level := 1; if true { level := 2; _ = level }; fmt.Println(level)

    The inner := declares a new level that only exists inside the if block. The outer level is never touched, so it still prints 1.
  5. 5. What does var s []int give you?

    The zero value of a slice is nil. It has length 0 and capacity 0, and append works on it normally.

Summary

  • Declare variables with var name type = value (type or value may be omitted, but not both) or, inside functions, with name := value.
  • := infers the type: int, float64, string, bool or rune for plain literals. Use var or a conversion to get another type.
  • Several variables can be declared or assigned at once, and a, b = b, a swaps without a temporary.
  • Every variable starts at its type's zero value: false, 0, "" or nil, and structs and arrays are zeroed field by field. Design your own types so the zero value is useful.
  • In a, err := ..., at least one name on the left must be new; the others are reused. A := in an inner block creates a new, shadowing variable.
  • Unused local variables are compile errors. Use _ to discard a value on purpose.

Next: Constants and iota