2.1 Declare Go Variables with var, :=, and const

2.1 Declare Go Variables with var, :=, and const

TL;DR

  • Use var to be explicit about a variable, especially when you don't have a value for it yet.
  • Use := for a quick and clean way to declare and assign a variable inside a function.
  • Use const for values that you know will never, ever change, like the value of Pi.

Why This Matters

Every program needs to remember things. Whether it's a user's name, the score in a game, or the price of an item, you need a way to store that information. In programming, we use variables to do this. Think of them as labeled boxes where you can keep data.

Go gives you three simple tools to create these boxes: var, :=, and const. Learning which one to use and when will make your code cleaner, safer, and easier to understand. It's one of the first and most important steps in writing any Go program.


Concepts in Plain English

Before we dive in, let's get a few key ideas straight. These are the building blocks for everything that follows.

  • Variable: A named container that holds a value that can change.
    • Analogy: A whiteboard where you can write down a number, erase it, and write a new one. The label "Today's Temperature" stays the same, but the value changes.
  • Declaration: The act of creating a new variable and giving it a name and a type.
    • Analogy: You grab an empty box and put a label on it, like "Dog Toys." You're declaring that this box exists for a specific purpose.
  • Initialization: The act of putting an initial value into a variable when you declare it.
    • Analogy: The moment you put the first toy into the "Dog Toys" box.
  • Constant (const): A named container that holds a value that cannot change.
    • Analogy: Your birthday. It's a fixed date that's assigned to you and never changes.

Here’s a quick reference table.

TermSimple DefinitionWhere It Shows Up
varThe classic, formal way to declare a variable.Anywhere in your code.
:=A shorthand to declare and initialize a variable.Only inside functions.
constA way to declare a value that is fixed and unchangeable.Anywhere in your code.
TypeThe kind of data a variable can hold (e.g., text, number).var name string, var age int

Do It Step by Step

Let's look at how to use each of these in practice. We'll start with the most traditional way and move to the shortcuts.

1. The Classic Way: var

The goal here is to formally declare a variable. You're telling Go, "Hey, I need a box of this specific type, and here's its name."

Declare and initialize at the same time.This is more common. You create the box and put something in it all in one step.

// Declare a variable named 'playerName' to hold text (a string)
// and give it an initial value of "Alex".
var playerName string = "Alex"

Assign a value later.After declaring it, you can put a value in the box whenever you're ready.

// Now, let's give the 'score' variable a value.
score = 100

Declare a variable without a value.Go will automatically give it a "zero value" (like 0 for numbers or an empty string for text).

// Declare a variable named 'score' that will hold an integer.
// It automatically gets the value 0.
var score int
Pro tip — Use var when you need to declare a variable at the top of your file (outside of any function) or when you know you'll need the variable but don't have its value yet.

2. The Short Way: :=

The goal is to write less code. The := operator is a handy shortcut that lets you declare and initialize a variable in one go, and it even figures out the type for you.

Use := to declare and initialize.This single line does the same work as var playerName string = "Alex" but is shorter.

// Go sees "Hello!" is a string and makes the 'greeting'
// variable a string type automatically.
greeting := "Hello!"
Warning — This shortcut only works inside a function. If you try to use := at the top level of your file, Go will complain.

This := operator is a big reason why Go code often feels so clean and lightweight.

Here’s a quick comparison:

Featurevar:= (Short Declaration)
Usage LocationAnywhere (inside or outside functions)Only inside functions
Type Needed?Optional (if you provide a value)No (Go figures it out)
Best ForDeclaring variables outside functions, or declaring a variable without an initial value.Most variable declarations inside functions.
Examplevar score intscore := 0

3. The Unchanging Way: const

The goal is to define a value that should never be changed during the program's run. This prevents accidental mistakes and makes your code's intentions clear.

Try to change it (and watch it fail).If you try to assign a new value to a constant, Go will stop you with an error. This is a good thing! It's protecting you from yourself.

// This line will cause a compile error!
// pi = 3.14 // Error: cannot assign to pi

Declare a constant with const.Once you set it, it's locked in.

// Define a constant for the company name.
// It's a string that will never change.
const companyName = "The Calm Builder Inc."

// Define a mathematical constant.
const pi = 3.14159

Examples Section

Let's put it all together in a small, runnable program.

Example A: A Simple Mix

This program shows all three declaration types working together inside a main function. You can copy and paste this into a file named main.go and run it.

package main

import "fmt"

// 'version' is declared outside any function, so we MUST use 'var' or 'const'.
const version = "1.0"

func main() {
    // We use 'var' because we'll get the user's name later.
    // It starts as an empty string "".
    var userName string

    // We use ':=' for a quick, local variable.
    // Go knows 10 is an integer.
    points := 10

    // Now we assign a value to userName.
    userName = "Casey"

    // Print everything out.
    fmt.Println("Welcome,", userName)
    fmt.Println("You have", points, "points.")
    fmt.Println("App Version:", version)
}

What you should see:

Welcome, Casey
You have 10 points.
App Version: 1.0

Example B: Choosing the Right Tool

Here's a diagram to help you decide which declaration to use.

flowchart LR
    A[Start] --> B{Will the value change?};
    B -- No --> C[Use const];
    B -- Yes --> D{Are you inside a function?};
    D -- Yes --> E[Use colon equals :=];
    D -- No --> F[Use var];

ASCII Fallback:

Start -> Will its value change?

  • If NO -> Use const.
  • If YES -> Are you inside a function?
    • If YES -> Use :=.
    • If NO -> Use var.

This simple flowchart covers about 99% of the cases you'll encounter. When in doubt, start here.


Common Pitfalls

  1. Using := outside a function. Remember, the := shortcut is for local variables inside a function body. For global variables at the package level, you must use var or const.
  2. Redeclaring a variable with :=. You can only use := the first time you create a variable. If you want to change its value later, just use = (a single equals sign).
    • score := 100 // Correct on the first declaration
    • score := 150 // WRONG: no new variables on left side of :=
    • score = 150 // CORRECT way to update the value
  3. Declaring a variable and not using it. Go is very strict about clean code. If you declare a variable (especially with :=), you must use it somewhere. If you don't, your code won't compile. This helps you avoid leftover, unused junk in your programs.

FAQ

  1. Can I declare multiple variables at once?
    • Yes! You can group them in a block with var or declare multiple on one line with :=.
// With var
var (
    name = "Sam"
    age = 42
)

// With :=
host, port := "localhost", 8080
  1. What happens if I use var but don't give the variable a value?
    • Go assigns it a "zero value." For numbers this is 0, for strings it's "" (an empty string), and for booleans it's false. It's a safety feature so your variables always have a predictable, neutral state.
  1. Why does Go have both var and :=?
    • It's about balancing clarity and convenience. var is very explicit and formal. := is a convenient shorthand that reduces clutter inside functions, where you declare lots of temporary variables.
  1. When is it better to use var even inside a function?
    • The main reason is when you need to declare a variable but don't have its value yet. For example, you might declare var err error at the top of a function and only assign a value to it inside an if block later on.

Recap

You've learned the three essential ways to create variables and constants in Go.

  • var is your formal tool. Use it outside functions or when you need to declare a variable before you know its value.
  • := is your everyday shortcut. Use it inside functions for fast, readable code. It's the most common way you'll declare variables in Go.
  • const is for permanent values. Use it for anything that should not be changed, making your code safer and clearer.

Start by using := for almost everything inside your functions. As you encounter situations where a value must not change or a variable is needed outside a function, you'll know it's time to reach for const or var.