---
date: 2026-07-19
---

<!-- markdownlint-disable MD001 -->

# Variables in Go

## What is a Variable?

A **variable** is a named container that stores a value. Think of it like a labeled box — you put something in it, and you can refer to it later by the label on the outside.

In Go, you can declare variables in **two main ways**: using the `var` keyword, or using the short-hand `:=` operator.

---

## Method 1: Using `var`

The `var` keyword is the most explicit way to declare a variable.

### Basic syntax

```go
var name string = "Gabe"
var age int = 28
```

Breaking that down:

| Part       | Meaning                                              |
| ---------- | ---------------------------------------------------- |
| `var`      | Keyword that says "I'm declaring a variable"         |
| `name`     | The variable's name (what you'll use to refer to it) |
| `string`   | The **type** — what kind of data it holds            |
| `= "Gabe"` | The **value** assigned to the variable               |

### Type inference

You don't always need to write the type. Go can figure it out from the value:

```go
var name = "Gabe"   // Go knows this is a string
var age = 28         // Go knows this is an int
var price = 19.99    // Go knows this is a float64
```

Here Go looks at the value you provided and infers the type automatically. This is called **type inference**.

### Zero values

If you declare a variable with `var` but **don't give it a value**, Go assigns a default "zero value":

```go
var name string    // "" (empty string)
var age int        // 0
var active bool    // false
var price float64  // 0.0
```

This is really handy — unlike some other languages, you'll never have an "uninitialized" variable in Go.

### Multiple variables at once

You can declare several variables in one line:

```go
var name, age = "Gabe", 28
```

Or group them in a block for readability:

```go
var (
    name    string
    age     int
    active  bool
)
```

---

## Method 2: Using `:=` (Short Declaration)

The `:=` operator is a shorthand. It does two things at once: **declares** the variable and **infers** its type.

```go
name := "Gabe"
age := 28
price := 19.99
```

This is equivalent to writing:

```go
var name = "Gabe"
var age = 28
var price = 19.99
```

Go figures out the type from the value on the right side.

### Multiple variables with :=

```go
name, age := "Gabe", 28
```

### Reassigning with `=`

Once a variable is declared, you reassign it with plain `=` (not `:=`):

```go
name := "Gabe"
name = "Gabriel"   // ✅ OK — reassigning

name := "Gabriel"  // ❌ Error — no new variables on left
```

### A special rule: `:=` with at least one new variable

`:=` works as long as **at least one** variable on the left is new:

```go
name := "Gabe"
age  := 28

name, city := "Gabriel", "Seattle"  // ✅ OK — city is new
```

This is very common with functions that return multiple values (like errors):

```go
data, err := doSomething()  // both data and err are new
data, err := doSomethingElse()  // ✅ OK — err is reused, but only need one new
```

---

## `var` vs `:=` — When to Use Which

| Situation                                             | Use         | Why                                     |
| ----------------------------------------------------- | ----------- | --------------------------------------- |
| Inside a function, and you know the value immediately | `:=`        | Short and clean                         |
| Inside a function, but you want a **zero value**      | `var`       | `:=` requires a value                   |
| Package-level (outside any function)                  | `var`       | `:=` is not allowed outside functions   |
| You want to be explicit about the type                | `var`       | You can write `var score float64 = 3.5` |
| Declaring multiple related variables in a block       | `var` block | Cleaner grouping                        |

### Examples of each

```go
package main

import "fmt"

// Package-level — must use var
var appVersion = "1.0.0"

// Grouped var block
var (
    appName    = "MyApp"
    buildDate  = "2026-07-19"
)

func main() {
    // Inside a function — := is preferred
    username := "gabe"
    age := 28

    // When you want a zero value
    var count int    // count = 0
    var message string  // message = ""

    // When you want to be explicit
    var price float64 = 19.99

    fmt.Println(username, age, count, message, price)
}
```

---

## Common Pitfalls

### 1. Using `:=` outside a function

```go
package main

version := "1.0"  // ❌ Syntax error — := not allowed here
var version = "1.0"  // ✅ OK
```

### 2. Redeclaring with `:=` when no new variable exists

```go
name := "Gabe"
name := "Gabriel"  // ❌ No new variables on left side
```

Fix: use `=` instead.

### 3. Using `=` before the variable is declared

```go
name = "Gabe"  // ❌ name hasn't been declared yet
var name string
```

Go doesn't allow this — the declaration must come first.

### 4. Declaring a variable and never using it

```go
name := "Gabe"
age := 28
fmt.Println(name)
// ❌ Compiler error: age declared but not used
```

Go treats unused variables as errors. This is intentional — it keeps your code clean. Either use `age` or remove it.

---

## Putting It All Together

Here's a complete program that demonstrates everything:

```go
package main

import "fmt"

// Package-level variables
var appName = "Variable Demo"

func main() {
    // Method 1: var with explicit type
    var message string = "Hello, Go!"

    // Method 2: var with inference
    var count = 3

    // Method 3: short declaration (most common inside functions)
    name := "Gabe"
    age := 28
    height := 1.85

    // Zero values
    var score int
    var active bool

    fmt.Println(appName)
    fmt.Println(message)
    fmt.Println("Count:", count)
    fmt.Println("Name:", name)
    fmt.Println("Age:", age)
    fmt.Println("Height:", height)
    fmt.Println("Score (zero value):", score)
    fmt.Println("Active (zero value):", active)
}
```

Run it:

```bash
go run main.go
```

Output:

```text
Variable Demo
Hello, Go!
Count: 3
Name: Gabe
Age: 28
Height: 1.85
Score (zero value): 0
Active (zero value): false
```

---

## Quick Reference

| Syntax                 | Example                    | Where allowed         | Type required? |
| ---------------------- | -------------------------- | --------------------- | -------------- |
| `var` + type + `=`     | `var name string = "Gabe"` | Anywhere              | No (optional)  |
| `var` + `=` (inferred) | `var name = "Gabe"`        | Anywhere              | No             |
| `var` (zero value)     | `var name string`          | Anywhere              | Yes            |
| `:=` (short)           | `name := "Gabe"`           | Inside functions only | No (inferred)  |

---

## Up Next

Now that you know how to store values, the next post will cover **Go's basic data types** — strings, ints, floats, and booleans — and how they behave. Stay tuned!
