Variables and basic types

Go · Essentials · 10 min

Go's static typing, zero values and lack of implicit conversion shape every line you write.

Go has two ways to declare a variable:

  • var count int declares with an explicit type; var name = "Ann" infers it. var works at package level and inside functions.
  • count := 0 is the short declaration, inferring the type. It only works inside functions and is what you'll use most of the time.

Every variable starts at its zero value — there is no "uninitialized" state. Numbers are 0, bool is false, string is "", and pointers, slices, maps, channels, functions and interfaces are nil. Good Go types are designed so the zero value is useful.

The basic types:

  • int, int8…int64, uint, uint8…uint64. int is 64 bits on all common platforms; use it unless you need a specific size.
  • float64 (prefer it) and float32; complex128.
  • bool, string, plus aliases byte (= uint8) and rune (= int32, a Unicode code point).

Go performs no implicit conversions, even between int and int64 or int and float64. You convert explicitly with T(x): float64(n) / 2. Converting a float to an int truncates toward zero.

:= needs at least one new variable on its left. In an inner block it creates a new variable that shadows the outer one — a classic source of bugs when you meant to assign with =.

Use fmt.Printf("%T %v\n", x, x) to print a value's type and value while you experiment.

Example

package main

import "fmt"

func main() {
	var total int // zero value: 0
	price := 2.5  // float64
	qty := 3      // int
	name, ok := "tea", true

	total = int(price * float64(qty)) // explicit conversions
	fmt.Println(total, name, ok)      // 7 tea true

	var s string
	fmt.Printf("%q %T\n", s, qty) // "" int
}

Remember

  • := inside functions, var when you need the zero value or package scope
  • Every type has a usable zero value; nothing is uninitialised
  • No implicit numeric conversions — write float64(n)

Watch out for

  • Accidentally shadowing a variable with := inside an if or loop block.

Check yourself

  1. Given `a := 7` and `b := 2.0`, which expression compiles?

Sign in to answer, see the explanations, and get this lesson back as a quick review later.

Official docs: go.dev/ref/spec#Variable_declarations