👋 Hello there!
If you’re starting your journey with Go programming, one of the first things you’ll encounter is variables and constants.
Understanding the difference between var and const is crucial — and in this article, we’ll make it simple, fun, and practical with easy examples.
🟦 What is a Variable (var) ?
Think of a variable as an open box.
You can put something inside it, take it out, or replace it whenever you want.
In Go, we use var to define variables.
*Example in Go:
*
package main
import "fmt"
func main() {
var balls int = 5
fmt.Println("Initial balls:", balls)
balls = 10 // Changing the value
fmt.Println("Updated balls:", balls)
}
Here, we have a box with 5 balls. Later, we replace them with 10 balls, and Go is totally fine with it.
*✔️ Use var when:
*
1- The value will change during program execution
2- You’re storing user inputs, counters, scores, etc.
🟩 What is a Constant (const)?
A constant is like a locked box.
Once you put a value inside, it cannot change for the lifetime of your program.
Example in Go:
package main
import "fmt"
func main() {
const pi float64 = 3.14
const userName string = "Ahmed"
fmt.Println("Pi:", pi)
fmt.Println("Username:", userName)
}
Try to change pi or userName later, and Go will give you an error — the value is locked.
.
🧠 Simple Analogy
Open box **(var) → like a desk drawer
**Locked box (const) → like a safe
*Real-life example:
*
1- var → drawer with papers
2- const → safe with your passport
🧭 When to Use var vs const in Go
*Use var for values that:
*
1- Change over time
2- Depend on user input
3- Work as counters, states, etc.
*Use const for values that:
*
1- Never change
2- Represent math constants
3- Define configuration values
4- Hold static names/labels
*💡 Pro Tip:
* 🚀 Always use const when possible — it keeps your Go code clean, safe, and bug-free.
✨ Final Thoughts
That was a simple and fun 😁 tour of variables (var) and constants (const) in Go.
😎 Once you master the difference, your Go code becomes:
1- Cleaner
2- More maintainable
3- Less buggy
🙌 Thanks for reading!
📢 Follow me on DEV
If you enjoyed this post, drop a ❤️ or leave a comment below — your support means a lot. Let’s connect and share ideas!
🙌 If you’ve got questions or topics for the next article, drop them in the comments — I reply to every one!
Stay curious. Stay coding.
And see you in the next article of the series: “Learn Go from Zero to Hero.”
`
`
Top comments (0)