Skip to Content
Skip to content
Go for Beginners: Write Reliable Programs and Small Services
Beginner
Courses
Go for Beginners: Write Reliable Programs and Small Services

Variables, Types, and Zero Values

Declare variables with var and :=, understand Go's predictable zero values, and tell strings, bytes, and runes apart. After this, you can read Go variable declarations without guessing their defaults.

Course content

Sign in to save your progress.

Course Home

In JavaScript, an uninitialized variable is undefined and "5" + 1 silently turns into "51". In Go, neither of those can happen. Every declared variable immediately gets a predictable zero value, and Go never implicitly converts between numeric types—even between int and float64.

Skip ahead

If you already know Go's zero values, why := can shadow outer variables, and how to convert between int, float64, and string with strconv, move on to "If, For Loops, and Multiple Return Values."

Experiment 1: Every type starts at a safe zero value

When you declare variables with var without assigning values, Go zeroes their memory cleanly instead of leaving garbage or crashing on read:

package main

import "fmt"

func main() {
	var count int
	var price float64
	var active bool
	var label string
	fmt.Printf("zeros: int=%d float=%.1f bool=%v string=%q\n", count, price, active, label)
}
zeros: int=0 float=0.0 bool=false string=""

That rule holds for every type in Go: numbers start at 0, booleans start at false, strings start at "", and reference types (pointers, slices, maps, channels, interfaces) start at nil. Because zero values are intentional, a struct like bytes.Buffer works immediately after var b bytes.Buffer with no constructor call.

Experiment 2: Explicit conversions and untyped constants

Suppose you have an integer item subtotal (1200 cents) and a 12% tax rate. If you declare var rate float64 = 0.12 and write subtotal * rate, Go refuses to compile: mismatched types int and float64. You must convert explicitly so truncation or precision loss never sneaks past you:

package main

import (
	"fmt"
	"strconv"
)

func main() {
	const taxRate = 0.12
	var subtotal int = 1200
	total := float64(subtotal) * (1 + taxRate)
	fmt.Printf("subtotal=%d total=%.2f\n", subtotal, total)

	n, err := strconv.Atoi("42")
	fmt.Printf("parsed=%d err=%v\n", n, err)
	bad, err := strconv.Atoi("42px")
	fmt.Printf("bad=%d err=%v\n", bad, err)
}
subtotal=1200 total=1344.00
parsed=42 err=<nil>
bad=0 err=strconv.Atoi: parsing "42px": invalid syntax

Look closely at two details here:

  • const taxRate = 0.12 is an untyped constant: It adapts cleanly to float64 (or float32) at the point of use. Once a value is in a typed var like subtotal int, you convert explicitly with float64(subtotal).
  • Strings do not convert with int("42"): Writing string(65) does not produce "65"—it produces the Unicode character "A" (code point 65)! Always use strconv.Itoa and strconv.Atoi to convert between decimal text and integers.

Experiment 3: The := shadowing trap inside blocks

Inside functions, := declares a new variable and infers its type automatically (limit := 10). That shortcut is great—until you accidentally write := inside an if or for block when you meant to reassign an outer variable with =:

package main

import "fmt"

func main() {
	limit := 10
	if true {
		limit := 99 // BUG: creates a brand-new inner variable!
		fmt.Println("inside if:", limit)
	}
	fmt.Println("outside if:", limit)
}
inside if: 99
outside if: 10

Trace why outside if still printed 10: limit := 99 declared a completely separate variable scoped only to the if block, leaving the outer limit untouched. Changing limit := 99 to limit = 99 updates the outer variable as intended.

When to use var vs. :=

  • Use := inside functions when initializing a variable with a clear starting value (port := 8080, name := "Ana").
  • Use var when you intentionally want the zero value (var total int), when you need a specific numeric width (var id int64), or at package scope (where := is not allowed).

Common mistakes

  • Shadowing an outer variable with := inside an if: Happens most often with val, err := doWork() inside a nested block when val was already declared outside.
  • Writing string(n) to format an integer: Converts an integer code point into a UTF-8 character instead of decimal digits; use strconv.Itoa(n) or fmt.Sprint(n).
  • Using float64 for money: Binary floating-point numbers cannot represent 0.10 exactly—store prices as integer cents (int64) in billing code.
  • Expecting if count to work like Python: Go booleans are strict; always write if count > 0.

💡 Tip

If you want to print any Go value during debugging with both field names and exact types, use fmt.Printf("%#v\n", x)—it prints Go-syntax output that immediately shows whether a value is int, int64, or string.

What happens if you skip this step

Shadowed variables inside if blocks fail silently with zero compiler errors—leaving your config or error variable stuck at its old value while the inner copy disappears. Understanding zero values, explicit conversions, and := vs. = prevents a whole class of silent logic bugs.

If you declare var port int outside an if block and write port, err := strconv.Atoi("8080") inside the if block, what is the value of the outer port right after the if block ends?

About

Declare variables with var and :=, understand Go's predictable zero values, and tell strings, bytes, and runes apart. After this, you can read Go variable declarations without guessing their defaults.

Duration
5 min
Last update
11/27/2026
Was this helpful?
​ 0 ​ 0

Comments

Sign in to comment

No comments yet.