How to Declare Variables in Go
Variables are how your programs remember things. Let's learn the different ways Go lets you create them.
Also available on YouTube • 19:50 watch time
What Is a Variable?
Think of a variable as a labeled container. You give it a name, and it holds a piece of data — a number, a word, a true-or-false value. Whenever your program needs that data, it looks up the variable by name and grabs whatever is inside.
The Two Ways to Declare Variables
Go gives you two approaches, and both are useful in different situations.
1. The Full Declaration
When you want to be explicit about what type of data a variable will hold:
var name string = "Bits Bytes"
var age int = 25
var isActive bool = true
Here you're telling Go exactly what you want: "Create a variable called name, it's a string, and its value is "Bits Bytes"." Crystal clear.
2. The Short-Hand Way
Inside functions, Go lets you skip the var keyword entirely using the := operator. Go figures out the type on its own:
name := "Bits Bytes"
age := 25
isActive := true
This is the style you'll see most often in Go code. It's shorter, cleaner, and Go is smart enough to know that "Bits Bytes" is a string and 25 is an integer.
Good to know: The := shorthand only works inside functions. If you're declaring a variable outside of a function (at the package level), you must use var.
Changing a Variable's Value
Once a variable exists, you can update its value using a simple = (no colon this time):
score := 10
fmt.Println(score) // prints 10
score = 25
fmt.Println(score) // prints 25
Notice: you only use := the first time. After that, just =. If you accidentally use := again with the same name, Go will complain.
Declaring Without Assigning
Sometimes you want to create a variable now and fill it in later. Go sets a default "zero value" for you:
var count int // default: 0
var message string // default: "" (empty)
var ready bool // default: false
This is handy when you know you'll need a variable but don't have the value yet — like when it depends on user input or a calculation that happens later.
Try It Yourself
Create a variable for your name, your age, and your favorite programming language. Print all three using fmt.Println. Then try changing one of them and printing again.