50 Mins

2. Go Variables and Data Types

Core Concept

Go is a statically typed language, but it features type inference, allowing you to omit type declarations in many cases. Go's type system is simple yet powerful, with clear and concise syntax. Variables in Go must be declared before use, and the language supports both explicit and implicit type declarations. Understanding Go's data types is fundamental to writing efficient and correct Go programs.

Go's basic data types include integers, floating-point numbers, booleans, and strings. The language also supports composite types like arrays, slices, maps, and structs. Go's type system is designed to be safe and efficient, with no implicit type conversions between incompatible types. This type safety helps prevent many common programming errors.

Basic Data Types and Variable Declaration

Go provides several built-in data types that form the foundation of the language. Integer types include int, int8, int16, int32, int64, uint, uint8, uint16, uint32, uint64, and uintptr. Floating-point types are float32 and float64. The bool type represents boolean values (true or false). The string type represents UTF-8 encoded text. Go also has byte (alias for uint8) and rune (alias for int32) for working with Unicode.

Variables in Go can be declared using the var keyword or the short declaration syntax (:=). The var keyword is used for explicit type declarations or when declaring multiple variables. The short declaration syntax infers the type from the initializer. Go also supports multiple variable declarations and type inference in one line.

Go
package main

import (
    "fmt"
    "reflect"
)

func main() {
    // Explicit variable declaration
    var age int = 25
    var name string = "Alice"
    var isActive bool = true

    // Type inference
    var city = "New York"
    var temperature = 72.5
    var count = 10

    // Short declaration (:=) - most common
    salary := 75000.50
    country := "USA"

    // Multiple declarations
    var x, y int = 10, 20
    var (
        firstName string = "John"
        lastName  string = "Doe"
        age2      int    = 30
    )

    // Zero values (default values)
    var defaultInt int
    var defaultFloat float64
    var defaultBool bool
    var defaultString string

    fmt.Printf("Name: %s, Age: %d, Active: %t
", name, age, isActive)
    fmt.Printf("City: %s, Temperature: %.1f, Count: %d
", city, temperature, count)
    fmt.Printf("Salary: $%.2f, Country: %s
", salary, country)
    fmt.Printf("x: %d, y: %d
", x, y)
    fmt.Printf("Full name: %s %s, Age: %d
", firstName, lastName, age2)

    // Zero values
    fmt.Printf("
Zero values:
")
    fmt.Printf("int: %d, float64: %f, bool: %t, string: %q
",
        defaultInt, defaultFloat, defaultBool, defaultString)

    // Type inference with reflect
    fmt.Printf("
Types:
")
    fmt.Printf("name: %s
", reflect.TypeOf(name))
    fmt.Printf("temperature: %s
", reflect.TypeOf(temperature))
    fmt.Printf("salary: %s
", reflect.TypeOf(salary))

    // Constant declaration
    const Pi = 3.14159
    const AppVersion string = "1.2.3"
    const (
        StatusOK = 200
        StatusNotFound = 404
        StatusError = 500
    )
    fmt.Printf("
Constants: Pi=%.5f, Version=%s
", Pi, AppVersion)
    fmt.Printf("Status codes: %d, %d, %d
", StatusOK, StatusNotFound, StatusError)

    // Iota enumerator
    const (
        Sunday = iota
        Monday
        Tuesday
        Wednesday
        Thursday
        Friday
        Saturday
    )
    fmt.Printf("Wednesday: %d
", Wednesday)

    return
}
OutputName: Alice, Age: 25, Active: true City: New York, Temperature: 72.5, Count: 10 Salary: $75000.50, Country: USA x: 10, y: 20 Full name: John Doe, Age: 30 Zero values: int: 0, float64: 0.000000, bool: false, string: "" Types: name: string temperature: float64 salary: float64 Constants: Pi=3.14159, Version=1.2.3 Status codes: 200, 404, 500 Wednesday: 3

Go's zero values are the default values assigned to variables that are declared but not initialized. The short declaration syntax (:=) is the most common way to declare variables in Go. Constants are declared with the const keyword and can be typed or untyped. The iota enumerator provides auto-incrementing values for constants.

Composite Types

Go provides composite types for grouping data together. Arrays are fixed-size sequences of elements of the same type. Slices are dynamic arrays that can grow and shrink. Maps are key-value pairs. Structs are collections of fields that can be used to group related data. Understanding these composite types is essential for building complex data structures.

Arrays in Go are value types, meaning they are copied when assigned. Slices are reference types and are more commonly used. Maps are reference types and provide O(1) average lookup time. Structs are the building blocks for creating complex data types and are often used with methods to implement object-oriented patterns.

Go
package main

import (
    "fmt"
    "reflect"
)

type Person struct {
    Name string
    Age  int
    City string
}

func main() {
    // Arrays (fixed size)
    var numbers [5]int = [5]int{1, 2, 3, 4, 5}
    names := [3]string{"Alice", "Bob", "Charlie"}
    
    // Slices (dynamic arrays)
    var dynamic []int = []int{10, 20, 30}
    dynamic = append(dynamic, 40, 50)
    
    // Slice with make
    slice := make([]int, 5, 10) // length 5, capacity 10
    slice[0] = 1
    slice[1] = 2
    
    // Maps (key-value pairs)
    var scores map[string]int
    scores = make(map[string]int)
    scores["Alice"] = 95
    scores["Bob"] = 87
    
    // Map literal
    ages := map[string]int{
        "Alice": 30,
        "Bob":   25,
        "Charlie": 35,
    }
    
    // Structs
    person := Person{
        Name: "Alice",
        Age:  30,
        City: "New York",
    }
    
    // Anonymous struct
    point := struct {
        X, Y int
    }{X: 10, Y: 20}

    // Print everything
    fmt.Printf("Numbers: %v
", numbers)
    fmt.Printf("Names: %v
", names)
    fmt.Printf("Dynamic slice: %v
", dynamic)
    fmt.Printf("Slice with make: %v (len=%d, cap=%d)
", slice, len(slice), cap(slice))
    fmt.Printf("Scores: %v
", scores)
    fmt.Printf("Ages: %v
", ages)
    fmt.Printf("Person: %+v
", person)
    fmt.Printf("Point: %+v
", point)
    fmt.Printf("Person name: %s, age: %d
", person.Name, person.Age)
    
    // Checking if key exists in map
    if value, ok := ages["Alice"]; ok {
        fmt.Printf("
Alice exists in map with age: %d
", value)
    }
    
    if value, ok := ages["David"]; !ok {
        fmt.Printf("David does not exist in map
")
    }

    // Iterating over map
    fmt.Printf("
Iterating over map:
")
    for key, value := range ages {
        fmt.Printf("  %s: %d
", key, value)
    }
    
    // Iterating over slice with index
    fmt.Printf("
Iterating over slice:
")
    for i, value := range dynamic {
        fmt.Printf("  dynamic[%d] = %d
", i, value)
    }

    return
}
OutputNumbers: [1 2 3 4 5] Names: [Alice Bob Charlie] Dynamic slice: [10 20 30 40 50] Slice with make: [1 2 0 0 0] (len=5, cap=10) Scores: map[Alice:95 Bob:87] Ages: map[Alice:30 Bob:25 Charlie:35] Person: {Name:Alice Age:30 City:New York} Point: {X:10 Y:20} Person name: Alice, age: 30 Alice exists in map with age: 30 David does not exist in map Iterating over map: Alice: 30 Bob: 25 Charlie: 35 Iterating over slice: dynamic[0] = 10 dynamic[1] = 20 dynamic[2] = 30 dynamic[3] = 40 dynamic[4] = 50

Arrays have fixed size and are value types. Slices are dynamic and reference types, making them more flexible. Maps provide key-value storage with O(1) average access. Structs group related data and can have methods attached. The range keyword simplifies iteration over slices, maps, and arrays.

Knowledge Check

Ready to test your understanding of 2. Go Variables and Data Types?

Back