# Variables and Constants

Course: [Go](https://www.devtutorials.ai/learn/go) · Section: Go Foundations
Source: https://www.devtutorials.ai/learn/go/foundations/variables-and-constants

> How to declare, initialize and change variables with var and :=, make constants with const and iota, name things, and ignore values with the blank identifier.

## What Are Variables?

**Variable** = a named box in memory that holds a value.

- The **name** lets you find the box again.
- The **value** is what is inside the box now.
- The value can change while the program runs.

For example:

- `name` holds `"Asha"`
- `marks` holds `92`
- `passed` holds `true`

**Simple lesson:** a variable is a labelled box that keeps a value for your program.

### A Real-World Example

Think of the school library register.

- Each row has a label: **Book**, **Student**, **Due date**.
- The librarian writes a value next to each label.
- When the book comes back, she rubs out the due date and writes a new one.

Now the mapping:

- **Label** = the variable's name.
- **What is written** = the variable's value.
- **Rubbing out and writing again** = changing the value.

In Go, every variable also has a **type**: the kind of value it can hold.

- `int` holds whole numbers, like `92`.
- `string` holds text, like `"Asha"`.
- `bool` holds `true` or `false`.

You will learn all the types in **Data Types**.

## What You Will Learn

In this lesson, you will learn:

1. How to declare, initialize, assign and reassign variables.
2. The three ways to declare variables: `var`, `:=`, and many at once.
3. How to make constants with `const`, and number them with `iota`.
4. The rules for naming things, and Go's keywords.
5. How to ignore a value with the blank identifier `_`.

## Working with Variables

### Variable Declaration

**Declaration** = telling Go: "make a new box with this name and this type".

```go runnable title="Declare a variable"
package main

import "fmt"

func main() {
	var marks int
	fmt.Println(marks)
}
```

```text
0
```

- `var` is the keyword that makes a variable.
- `marks` is the name. `int` is the type.
- We gave no value, so Go put the **zero value** of `int`, which is `0`.
- You will learn zero values in **Data Types**.

### Variable Initialization

**Initialization** = giving a variable its first value when you make it.

```go runnable title="Declare and initialize"
package main

import "fmt"

func main() {
	var name string = "Asha"
	var marks int = 92
	fmt.Println(name, marks)
}
```

```text
Asha 92
```

### Variable Assignment and Reassignment

**Assignment** = putting a value into a variable with `=`.

**Reassignment** = putting a new value into a variable that already has one.

- The old value is gone.
- The **type** cannot change: an `int` box only takes whole numbers.

Press **Play** and watch the box change.

Watch two things:

- **Memory:** the value in the box changes, but the name stays.
- **Output:** each `Println` shows the value at that moment.

### A Wrong Type Is Not Allowed

Run this. It puts text into an `int` box.

```go runnable expect-error title="Wrong type"
package main

import "fmt"

func main() {
	var marks int = 70
	marks = "eighty"
	fmt.Println(marks)
}
```

- Go stops before running anything.
- The real `go` tool says: `cannot use "eighty" (untyped string constant) as int value in assignment`.
- Fix: keep the same type, like `marks = 80`.

**Simple lesson:** declare a box, give it a value, and change the value later, but never its type.

## Variable Declaration Forms

Go has a few ways to make variables.
Click each tab and compare.

### The var Keyword

- `var name type = value` is the full form.
- You can leave out the type, or the value, but not both.
- Use `var` when you want the zero value, like `var count int`.

### Short Variable Declaration (:=)

**`:=`** = declare **and** initialize in one step, inside a function.

```go runnable title="Short declaration"
package main

import "fmt"

func main() {
	student := "Ravi"
	class := 8
	present := true
	fmt.Println(student, class, present)
}
```

```text
Ravi 8 true
```

- `:=` makes a **new** variable.
- `=` changes a variable that **already exists**.
- At least one new name must be on the left of `:=`.

`:=` does not work outside a function.

At the top of a file, write `var school = "Green Valley"` instead.

### Multiple Variable Declarations

You can make many variables in one line, or in a group.

```go runnable title="Many variables at once"
package main

import "fmt"

var (
	school = "Green Valley School"
	city   = "Pune"
)

func main() {
	var maths, science int = 91, 88
	name, class := "Meena", "8A"
	fmt.Println(school, city)
	fmt.Println(name, class, maths, science)
}
```

```text
Green Valley School Pune
Meena 8A 91 88
```

- `var ( ... )` groups many variables neatly.
- `a, b := 1, 2` gives values in the same order: `a` gets `1`, `b` gets `2`.

### Swapping Two Values

Go can assign many values at once.
This makes swapping easy.

```go runnable title="Swap two values"
package main

import "fmt"

func main() {
	first, second := "Asha", "Ravi"
	first, second = second, first
	fmt.Println(first, second)
}
```

```text
Ravi Asha
```

- Go reads **all** the values on the right first.
- Then it puts them into the boxes on the left.

**Simple lesson:** use `:=` inside functions, and `var` outside them or when you want a zero value.

## Constants

**Constant** = a named value that can never change.

Some school facts never change:

- the number of days in a week: `7`
- the pass mark: `35`
- the school's name

### The const Keyword

```go runnable title="Make constants"
package main

import "fmt"

const passMark = 35
const school = "Green Valley School"

func main() {
	const daysInWeek = 7
	fmt.Println(school, passMark, daysInWeek)
}
```

```text
Green Valley School 35 7
```

- `const` makes a constant.
- A constant needs its value when you make it.
- The value must be known before the program runs, like `35` or `"text"`.

Now try to change one:

```go runnable expect-error title="A constant cannot change"
package main

import "fmt"

func main() {
	const passMark = 35
	passMark = 40
	fmt.Println(passMark)
}
```

- Go stops: `cannot assign to passMark`.
- That is the point of a constant: no one changes it by mistake.

### Typed and Untyped Constants

**Untyped constant** = a constant with no fixed type yet. Go gives it a type where you use it.

```go runnable title="An untyped constant fits many types"
package main

import "fmt"

const half = 0.5

func main() {
	var price float64 = 80
	var weight float32 = 3
	fmt.Println(price*half, weight*half)
}
```

```text
40 1.5
```

- `half` works with a `float64` **and** a `float32`.
- A typed constant `const half float64 = 0.5` would fail with the `float32`.

### iota

**`iota`** = a counter that Go uses inside a `const ( )` group. It starts at `0` and goes up by `1` on each line.

It is great for numbering things, like the days of a timetable.

You can also do maths with `iota`:

```go runnable title="iota with maths"
package main

import "fmt"

const (
	_  = iota
	KB = 1 << (10 * iota)
	MB = 1 << (10 * iota)
)

func main() {
	fmt.Println(KB, MB)
}
```

```text
1024 1048576
```

- The first line uses `_`, so `0` is thrown away.
- `KB` gets `iota = 1`, `MB` gets `iota = 2`.
- `<<` doubles a number many times. You will learn it in **Operators**.

**Easy way to remember**

- `var` = a box whose value can change.
- `const` = a box that is sealed forever.
- `iota` = an automatic counter for a `const` group.

**Simple lesson:** use `const` for values that never change, and `iota` to number them for you.

## Identifiers and Keywords

**Identifier** = a name you choose, for a variable, a constant or a function.

### Naming Rules

- Use letters, digits and `_` only.
- Start with a letter or `_`, never a digit.
- No spaces, and no symbols like `-` or `@`.
- Capital letters matter: `marks` and `Marks` are two different names.
- Do not use a keyword as a name.

| Name | Allowed? | Why |
|---|---|---|
| `totalMarks` | Yes | Letters only. |
| `class8A` | Yes | Digits are fine after the first letter. |
| `_temp` | Yes | Can start with `_`. |
| `8A` | No | Starts with a digit. |
| `total-marks` | No | `-` is the minus sign. |
| `func` | No | It is a keyword. |

### Naming Style

Go programmers use **camelCase**:

- start small, then capital at each new word: `studentName`, `totalMarks`
- short names for short jobs: `i` for a loop counter
- clear names for long jobs: `attendanceCount`, not `ac`

### Keywords

**Keyword** = a word Go keeps for itself. You cannot use it as a name.

Go has 25 keywords:

```text
break     default      func     interface   select
case      defer        go       map         struct
chan      else         goto     package     switch
const     fallthrough  if       range       type
continue  for          import   return      var
```

### Exported vs Unexported Identifiers

The first letter of a name decides who can see it:

- **Capital first letter** (`Total`) = **exported**: other packages can use it.
- **Small first letter** (`total`) = **unexported**: only this package can use it.
- This is why we write `fmt.Println`, with a capital `P`.
- You will learn this fully in **Packages and Modules**.

**Simple lesson:** names use letters, digits and `_`, start with a letter, and the first letter's case decides who can see them.

## The Blank Identifier

**Blank identifier** = `_`, a name that means "throw this value away".

### Unused Variables Are Not Allowed

Go does not allow a variable you never use.
Run this.

```go runnable expect-error title="An unused variable"
package main

import "fmt"

func main() {
	name := "Asha"
	age := 13
	fmt.Println(name)
}
```

```text
./prog.go:7:2: declared and not used: age
```

- `7:2` means line 7, column 2.
- Fix: use `age`, or delete it.
- Go is strict here to keep code clean.

### Ignoring Return Values

Some functions give back **two** values.
If you need only one, put `_` in place of the other.

```go runnable title="Ignore a value with _"
package main

import "fmt"

func main() {
	count, _ := fmt.Println("Hello")
	fmt.Println("Bytes printed:", count)
}
```

```text
Hello
Bytes printed: 6
```

- `fmt.Println` gives back two values: how many bytes it printed, and an error.
- We keep the count and throw the error away with `_`.
- `Hello` plus the new line is 6 bytes.

### Ignoring Unused Values

You can also use `_` to skip a value in a list:

```go runnable title="Skip the middle value"
package main

import "fmt"

func main() {
	name, _, city := "Kavya", 13, "Mysuru"
	fmt.Println(name, city)
}
```

```text
Kavya Mysuru
```

**Simple lesson:** every variable must be used, and `_` is how you say "I do not need this value".

## TL;DR

1. **Variable** = a named box whose value can change.
   - Declare: `var marks int`
   - Initialize: `var marks int = 90`
   - Short form inside functions: `marks := 90`
   - Reassign: `marks = 95` (same type only)
2. **Constant** = `const passMark = 35`. It never changes.
   - **Untyped** = no fixed type, fits where it is used.
   - **iota** = counter in a `const ( )` group: 0, 1, 2, ...
3. **Identifier** = a name: letters, digits, `_`, not starting with a digit.
   - Capital first letter = exported.
4. **Keyword** = one of Go's 25 reserved words.
5. **Blank identifier** = `_`, throws a value away.

## Common mistakes

| Mistake | Wrong idea | Correct idea | What goes wrong |
|---|---|---|---|
| `count := 5` at the top of a file | `:=` works everywhere | `:=` works only inside functions | `syntax error: non-declaration statement outside function body` |
| `marks := 90` twice in one block | `:=` can change a value | Use `=` to change an existing variable | `no new variables on left side of :=` |
| `marks = "ninety"` | A variable can change type | The type is fixed forever | `cannot use "ninety" ... as int value` |
| An unused variable | Extra variables are harmless | Every variable must be used | `declared and not used` |
| Changing a constant | `const` is like `var` | A constant never changes | `cannot assign to passMark` |
| `total-marks := 10` | `-` can join words | Use camelCase: `totalMarks` | A syntax error. |
| `Marks` vs `marks` | Case does not matter | They are two different names | `undefined: marks` |

## Check Yourself

## Exercises

## What to Remember

- A variable is a named box. Its value can change, but its type cannot.
- Inside functions, `:=` is the short way to make a variable. Use `=` to change it.
- `const` makes a value that never changes. `iota` numbers a `const` group.
- Names use letters, digits and `_`. A capital first letter means exported.
- Every variable and import must be used. Use `_` to throw a value away.

Next: **Data Types**. You will learn the kinds of values Go can store, their zero values, and how to convert between them.
