Web Analytics

Variables & Types

Beginner ~35 min read

Variables are the foundation of any programming language. In this lesson, you'll learn how to declare variables in Go, understand Go's type system, and master type inference and conversions.

Go Variables and Types - Complete Hierarchy

Figure: Complete Go Variables & Types Hierarchy - Declarations, Basic Types, Composite Types, Reference Types, and Conversions

Variable Declaration with var

Go provides the var keyword for declaring variables. The syntax is:

var name type = value

Let's see it in action:

Output
Click Run to execute your code
Key Points:
  • var declares a variable
  • Type comes after the variable name (unlike C/Java)
  • You can initialize the variable immediately
  • Variables without initialization get their "zero value"

Zero Values

In Go, variables declared without an explicit initial value are given their zero value:

Type Zero Value Example
Numeric types (int, float64) 0 var count int → 0
Boolean (bool) false var active bool → false
String (string) "" (empty string) var name string → ""
Pointers, slices, maps, channels, functions, interfaces nil var ptr *int → nil
Best Practice: Zero values make Go programs safer. You never have uninitialized variables with random values like in C/C++!

Short Variable Declaration (:=)

Go provides a shorthand syntax using := for declaring and initializing variables inside functions:

Output
Click Run to execute your code
Short Declaration (:=) Rules:
  • Can only be used inside functions
  • Type is inferred from the value
  • More concise than var
  • Most common way to declare variables in Go

var vs := When to Use Which?

Use var Use :=
Package-level variables Local variables in functions
When you need to specify the type explicitly When type can be inferred
When declaring without initialization When initializing immediately
var count int count := 0

Go's Type System

Go is a statically typed language, meaning variable types are known at compile time. Here are the basic types:

Output
Click Run to execute your code

Numeric Types

Type Size Range/Description
int 32 or 64 bits Platform dependent (most common)
int8 8 bits -128 to 127
int16 16 bits -32,768 to 32,767
int32 32 bits -2 billion to 2 billion
int64 64 bits Very large numbers
uint, uint8, uint16, etc. Varies Unsigned (positive only)
float32 32 bits Single precision
float64 64 bits Double precision (default for decimals)

Other Basic Types

  • bool - Boolean values (true or false)
  • string - UTF-8 encoded text
  • byte - Alias for uint8
  • rune - Alias for int32, represents a Unicode code point

Type Inference

Go can automatically infer the type of a variable from its initial value:

// Type is inferred
message := "Hello"      // string
count := 42             // int
pi := 3.14159          // float64
isActive := true       // bool

// You can check the type using %T in Printf
fmt.Printf("Type of message: %T\n", message)  // string
fmt.Printf("Type of count: %T\n", count)      // int
fmt.Printf("Type of pi: %T\n", pi)            // float64
Pro Tip: When Go infers numeric types:
  • Integers default to int
  • Floating-point numbers default to float64

Type Conversion

Unlike some languages, Go requires explicit type conversion. There are no automatic conversions:

Output
Click Run to execute your code
Important: Type conversion syntax is Type(value), not (Type)value like in C/Java. For example: float64(x), not (float64)x.

Common Mistakes

1. Using := outside functions

// ❌ Wrong - syntax error
package main

count := 0  // Can't use := at package level

func main() {
    // ...
}

// ✅ Correct
package main

var count = 0  // Use var at package level

func main() {
    // ...
}

2. Redeclaring variables with :=

// ❌ Wrong - redeclaration
func main() {
    name := "Alice"
    name := "Bob"  // Error: no new variables on left side
}

// ✅ Correct - use = for reassignment
func main() {
    name := "Alice"
    name = "Bob"   // Reassignment, not declaration
}

3. Mixing types without conversion

// ❌ Wrong - type mismatch
var x int = 10
var y float64 = 3.14
result := x + y  // Error: mismatched types

// ✅ Correct - explicit conversion
var x int = 10
var y float64 = 3.14
result := float64(x) + y  // Works!

4. Unused variables

// ❌ Wrong - declared but not used
func main() {
    name := "Alice"  // Error: name declared but not used
    fmt.Println("Hello")
}

// ✅ Correct - use the variable or remove it
func main() {
    name := "Alice"
    fmt.Println(name)  // Now it's used
}

Exercise: Temperature Converter

Task: Create a program that converts temperatures between Celsius and Fahrenheit.

Requirements:

  • Declare a variable for Celsius temperature (use 25.0)
  • Convert to Fahrenheit using the formula: F = C × 9/5 + 32
  • Print both temperatures with proper labels
  • Use appropriate types (float64)
Show Solution
package main

import "fmt"

func main() {
    // Celsius temperature
    celsius := 25.0
    
    // Convert to Fahrenheit
    fahrenheit := celsius * 9/5 + 32
    
    // Print results
    fmt.Printf("%.1f°C = %.1f°F\n", celsius, fahrenheit)
    
    // Bonus: Convert back to verify
    celsiusCheck := (fahrenheit - 32) * 5/9
    fmt.Printf("%.1f°F = %.1f°C\n", fahrenheit, celsiusCheck)
    
    // Type information
    fmt.Printf("\nType of celsius: %T\n", celsius)
    fmt.Printf("Type of fahrenheit: %T\n", fahrenheit)
}

Summary

  • var keyword declares variables with explicit types
  • := operator provides short declaration with type inference (functions only)
  • Zero values ensure variables are always initialized (0, false, "", nil)
  • Type comes after the variable name in Go
  • Static typing means types are checked at compile time
  • Type inference automatically determines types from values
  • Explicit conversion required between different types
  • Unused variables cause compilation errors

What's Next?

Now that you understand variables and types, you're ready to learn about Constants & Operators. In the next lesson, you'll discover how to define immutable values and perform operations on your data.