Go Fundamentals

Lesson 2 of 8

Variables, Types and Constants

Go is statically typed, but leans hard on type inference so you rarely have to spell types out.

var xp int = 0        // explicit type
var name = "Ada"       // inferred as string
count := 5              // short declaration, inferred, only works inside functions
xp += 10

:= is the idiomatic way to declare and initialize a variable at the same time inside a function, Go infers the type from the right-hand side. var is used instead when you need to declare without initializing, or at the package level (outside any function), where := isn't allowed.

Zero values

Unlike many languages, an uninitialized Go variable is never garbage or undefined, it gets a sensible zero value automatically:

var count int      // 0
var name string     // "" (empty string)
var ready bool      // false

This eliminates an entire category of "uninitialized variable" bugs common in other languages.

Constants

const MaxRetries = 3
const Pi = 3.14159

const values are fixed at compile time and can never be reassigned, use them for values that should never change during a program's execution, like configuration limits.

📝 Variables and Constants Quiz

Passing score: 70%
  1. 1.What is the zero value of an uninitialized Go int?

  2. 2.The := short declaration operator can be used at the package level, outside any function.

  3. 3.A value declared with ____ is fixed at compile time and can never be reassigned.