Variables & Constants

🐹 Go Language Lesson 2 Beginner

Go is a statically-typed language with dynamic type inference. Go enforces clean code, requiring that every declared variable must be used, or the compiler will throw an error.

1 Short Declaration Operator (:=) & Zero Values

Variables in Go can be initialized in multiple ways:

  • Explicit Declaration: `var score int = 95`
  • Short Declaration Operator (`:=`): `score := 95` (Automatically infers the type as integer. Can only be used inside function bodies).
  • Zero Values: If you declare a variable without assigning a value (e.g. `var count int`), Go automatically initializes it to its type's default "Zero Value" (`0` for integers, `0.0` for floats, `false` for booleans, and `""` for strings).
2 Variables Code

Let's run a program declaring variables and verifying zero-value defaults:

Go — Variables & Zero Values ▶ Run Code
package main

import "fmt"

func main() {
    // Short declaration
    message := "Golang is awesome!"
    
    // Explicit declarations showing zero values
    var age int
    var rate float64
    var active bool

    const pi = 3.14159 // Constant definition

    fmt.Println(message)
    fmt.Printf("Default Int: %d\n", age)
    fmt.Printf("Default Float: %.2f\n", rate)
    fmt.Printf("Default Bool: %t\n", active)
    fmt.Printf("Constant Pi: %f\n", pi)
}
3 Code Challenge
Challenge: Write a program declaring three variables: a name (string), a price (float64), and a stockCount (int) using the short declaration operator. Print all three variables to the console.