Go Gopher How to Go

Variables let you name values. Go uses explicit var declarations or short-hand := inside functions.

💡 Key Points

  • var allows explicit types or inferred types from the initializer.
  • := is only valid inside functions; it infers the type.
  • Multiple assignment is common for parallel declarations.
  • Uninitialized variables have their type's zero value, never undefined.
package main

import "fmt"

func main() {
	var a string = "initial"
	fmt.Println(a)

	var b, c int = 1, 2
	fmt.Println(b, c)

	var d = true // type inferred
	fmt.Println(d)

	var e int // zero value
	fmt.Println(e)

	f := "short" // short declaration inside functions
	fmt.Println(f)
}
Output:
initial
1 2
true
0
short

Variable Declaration Syntax

DeclarationExampleScopeDescription
var name typevar x intPackage or FunctionExplicit type, zero value initialized
var name = valuevar x = 10Package or FunctionType inferred from value
name := valuex := 10Function onlyShort declaration, type inferred
var a, b typevar x, y intPackage or FunctionMultiple variables, same type

Zero Values

TypeZero Value
int, int8, int16, int32, int640
float32, float640.0
boolfalse
string"" (empty string)
Pointers, slices, maps, channels, functions, interfacesnil