š 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! š¹