ProgramGuru

Variables

Start with Go Variables

A variable gives a name to a value that your program can read and update. Go variables have types, even when the compiler infers those types for you.

What you’ll learn

  • Declare variables with explicit types.
  • Differentiate declaration from assignment.
  • Describe type safety during updates.

Understand the idea

Use var name string = "Mina" to state a variable’s name, type and value. You can omit the type when the initial value makes the type clear: var age = 12. Inside a function, := is a shorter declaration form, covered in the next lesson.

Assignment uses =, not :=, once the variable exists. You cannot assign a string to an int variable because the types do not match.

Visualize how it works

Follow this diagram before executing the example. Check where a value or decision changes what runs next.

Visual explanation for variablesA variable has one current value; assignment changes that value.Declare age = 12Step 1Read ageStep 2Assign age = 13Step 3Read updated ageStep 4A variable has one current value; assignment changes that value.
A variable has one current value; assignment changes that value.

Run a complete Go example

This example is a complete program. Save it as main.go or paste it into the Go Playground.

Go code

package main

import "fmt"

func main() {
	var name string = "Mina"
	var age int = 12
	fmt.Println(name, "is", age)
	age = 13
	fmt.Println("Next age:", age)
}

Output

Mina is 12
Next age: 13

Trace what the program does

Go allocates variables with specific types. The first printing call reads both variables. Updating age replaces its previous value without declaring a new variable, so the second line reflects 13.

Avoid common mistakes

  • Use = to update an existing variable, not to declare a new one without var.
  • A variable declared inside a function must be used; unused locals cause compilation failure.

Try it yourself

Add an integer variable for the number of books the student owns and print it with the name.

Tip: Edit the example above, predict the output, and run the modified code to test your reasoning.

Check your understanding

How do you update an existing variable named age?
Choose one answer. You can try again.

Answer and explanation

age = 13

Correct. Go allocates variables with specific types.

What you should remember

You have practiced Go Variables in a small, self-contained program. The important habit is to predict what runs, inspect the actual output and distinguish the language rule from the particular example.

Before continuing, make sure you can explain the program to someone who has not seen it, including the line that changes its result.

Reaching the recap and completing the quizzes are separate milestones.

    Next lesson: Short Variable Declaration →