AnyCompiler

Variables and Types

Go has two ways to declare a variable: var name Type = value spells out the type explicitly, while name := value lets the compiler infer the type from the value — := is by far the more common style inside functions.

package main

import "fmt"

func main() {
	var age int = 30
	var price float64 = 19.99
	var isStudent bool = false
	name := "Alice"

	fmt.Println(name, age, price, isStudent)
}
Output
Alice 30 19.99 false

Zero values

Declare a variable with var and no initial value, and Go doesn't leave it uninitialized — every type has a zero value it starts with automatically: 0 for numbers, false for booleans, an empty string for strings. There's no equivalent of an undefined or null variable waiting to cause a crash.

package main

import "fmt"

func main() {
	var count int
	var label string
	var ready bool

	fmt.Println(count, label, ready)
}
Output
0  false

What a real compile error looks like

Go's compiler is strict about one thing in particular: a variable you declare but never use is a build error, not just a warning. This is genuinely what the compiler reports — captured from a real run, not written to look plausible:

package main

import "fmt"

func main() {
	message := "hello"
	fmt.Println("done")
}
Output
# command-line-arguments
./main.go:6:2: message declared and not used

Nothing runs at all — no output, just the error. Go's compiler enforces this deliberately: an unused variable is almost always a mistake (a leftover from refactoring, a typo'd name), so the compiler refuses to build until it's fixed.

Next: functions — func syntax, and Go's multiple return values.

Practice exercise

Declare a variable price := 9.99 and a variable inStock := true. Print them together with fmt.Println(price, inStock).