🏠 Variables & Constants in Go: Your Code’s Storage Boxes
Imagine you have a magic toy box in your room. Some boxes can hold different toys anytime you want (these are variables). But some special boxes are locked forever with one toy inside (these are constants). Today, we’ll learn how Go uses these boxes to store information!
📦 Variable Declaration: Labeling Your Box
Think of declaring a variable like putting a name tag on an empty box and telling everyone what type of toy goes inside.
var age int
var name string
var isHappy bool
Here’s what’s happening:
var= “Hey Go, I want a box!”age= the name tag on the boxint= only numbers allowed inside
The Full Declaration (With a Toy Inside!)
var score int = 100
var greeting string = "Hello!"
graph TD A["var keyword"] --> B["name: score"] B --> C["type: int"] C --> D["value: 100"]
⚡ Short Variable Declaration: The Quick Way
Tired of writing var every time? Inside functions, Go has a shortcut!
func main() {
name := "Gopher"
age := 5
isAwesome := true
}
The := is like saying: “Create a box, figure out what type it should be, and put this toy inside—all at once!”
Important: This only works inside functions, not outside!
graph TD A["name := 'Gopher'"] --> B["Go sees a string"] B --> C["Creates string box"] C --> D["Puts 'Gopher' inside"]
🎁 Multiple Variable Declaration: Many Boxes at Once
Why create boxes one by one when you can make many together?
Method 1: One Line, Same Type
var x, y, z int = 1, 2, 3
Method 2: Block Declaration
var (
firstName string = "Go"
lastName string = "Gopher"
age int = 10
)
Method 3: Short Way (Inside Functions)
a, b, c := 1, "hello", true
It’s like labeling three boxes and filling them all in one magical moment!
🌟 Zero Values: The Empty Box Gift
Here’s something beautiful about Go: every box comes with a free gift inside!
When you create a box but don’t put anything in it, Go automatically puts a “zero value” inside:
| Type | Zero Value | Think of it as… |
|---|---|---|
int |
0 |
An empty piggy bank |
float64 |
0.0 |
Zero dollars |
string |
"" |
A blank piece of paper |
bool |
false |
Light switch OFF |
var count int // count is 0
var message string // message is ""
var isReady bool // isReady is false
No surprises, no garbage—just clean, predictable starting values!
👻 Variable Shadowing: The Copycat Box
Imagine you have a toy named “Bear” in the living room. Then you go to your bedroom and name a different toy “Bear” too. In your bedroom, when you say “Bear,” you mean your bedroom Bear!
package main
import "fmt"
var message = "I'm outside!"
func main() {
message := "I'm inside!"
fmt.Println(message)
// Prints: I'm inside!
}
The inner message shadows (hides) the outer one. When you leave the bedroom (function), the original “Bear” is back!
graph TD A["Package Level"] --> B["message = 'I'm outside!'"] C["Function Level"] --> D["message = 'I'm inside!'"] D --> E["Shadows package message"] E --> F["Prints: I'm inside!"]
Warning: Shadowing can cause bugs if you’re not careful!
🔭 Scope Rules: Where Can Your Box Live?
Scope = the “room” where your box exists. A box can only be used in its room!
Package Scope (The Whole House)
package main
var houseKey = "secret123" // Everyone in main can see this
Function Scope (One Room)
func bedroom() {
var teddyBear = "Fluffy" // Only exists in bedroom
}
Block Scope (A Corner of the Room)
func main() {
if true {
var temp = "I live in the if-block only"
}
// temp doesn't exist here!
}
graph TD A["Package Scope"] --> B["Function Scope"] B --> C["Block Scope"] C --> D["Inner can see outer"] D --> E["Outer cannot see inner"]
Simple Rule: You can see out from a small room, but you can’t see into a small room from outside!
🔒 Constants: The Forever-Locked Box
Some values should never change. Like your birthday or the number of days in a week!
const Pi = 3.14159
const DaysInWeek = 7
const AppName = "GoLearner"
Try to change a constant? Go says NO! 🚫
const gravity = 9.8
gravity = 10.0 // ERROR! Cannot change constants!
Grouping Constants
const (
StatusOK = 200
StatusError = 500
MaxRetries = 3
)
🔢 iota: The Magic Counter
Here’s Go’s secret weapon: iota is like a automatic number machine that counts for you!
const (
Sunday = iota // 0
Monday // 1
Tuesday // 2
Wednesday // 3
Thursday // 4
Friday // 5
Saturday // 6
)
Every time you use iota in a const block, it starts at 0 and goes up by 1!
Skipping with iota
const (
_ = iota // Skip 0
Small // 1
Medium // 2
Large // 3
)
Powers of 2 (For Flags!)
const (
Read = 1 << iota // 1 (binary: 001)
Write // 2 (binary: 010)
Execute // 4 (binary: 100)
)
graph TD A["const block starts"] --> B["iota = 0"] B --> C["Each line: iota++"] C --> D["Sunday = 0"] D --> E["Monday = 1"] E --> F["Tuesday = 2"] F --> G["...and so on!"]
🎯 Quick Summary
| Concept | Think of it as… |
|---|---|
| Variable Declaration | Labeling a box with its type |
Short Declaration (:=) |
Quick box creation inside functions |
| Multiple Declaration | Making many boxes at once |
| Zero Values | Free default gifts in empty boxes |
| Shadowing | Same-name box hiding another |
| Scope | The room where a box lives |
| Constants | Locked boxes that never change |
| iota | Auto-counting number machine |
🚀 You Did It!
You now understand how Go stores and organizes information! Variables are your flexible storage boxes, constants are your locked treasures, and iota is your counting helper.
Remember: Good code is like a well-organized room—every box has its place, its name, and its purpose!
Next up, you’ll use these boxes to build amazing programs. Happy coding, young Gopher! 🐹
