Back to Blog

Variables & Data Types (var, :=, const, Zero Values) - Go Tutorial for Beginners #2 -

Sandy LaneSandy Lane

Video: Variables & Data Types (var, :=, const, Zero Values) - Go Tutorial for Beginners #2 - by Taught by Celeste AI - AI Coding Coach

Watch full page →

Variables & Data Types in Go: var, :=, const, and Zero Values

In Go, variables can be declared explicitly with the var keyword or more concisely using the short declaration operator :=, which infers the variable's type automatically. Constants are declared with const and cannot be changed once set. Additionally, Go assigns zero values to variables declared without an initial value, ensuring predictable defaults for basic types like strings, integers, floats, and booleans.

Code

// Explicit variable declaration with type
var name string = "Alice"
var age int = 25

// Short declaration with type inference
name := "Bob"
age := 30

// Declaring constants
const Pi = 3.14159
const AppName = "MyApp"

// Variables with zero values (default initialization)
var count int      // 0
var message string // ""
var flag bool      // false

Key Points

  • Use var to declare variables explicitly with their types.
  • The short declaration operator := infers the variable type automatically and is commonly used.
  • const declares immutable values that cannot be changed after assignment.
  • Uninitialized variables receive zero values: 0 for numbers, empty string for strings, and false for booleans.
  • Go’s zero values help avoid undefined or garbage data, making programs more reliable.