Blocks, Shadows, and Control Structures Flashcards
Where are global variables declared?
In the package block.
What happens when a variable has the same name as an outer variable?
It shadows the outer variable.
Can you access a shadowed variable?
No, scope limits prevent access.
What does :=
risk when declaring variables?
It may unintentionally shadow an outer variable.
What can shadowing affect besides variables?
Package imports (e.g., fmt).
What is the universe block?
The outermost block containing all built-ins.
Are built-ins in the universe block shadowable?
Yes, but avoid redefining them.
Does an if statement need parentheses around its condition?
No, the condition is bare.
How are variables scoped in an if statement?
They’re limited to the if block, e.g., if n := rand.Intn(10); n == 0 {...}
.
What is Go’s only looping construct?
The for
loop.
What are the three parts of a complete for
statement?
Init, compare, increment (e.g., i := 0; i < 10; i++
).
How does a condition-only for statement work?
Like a while loop, e.g., for i < 100 {...}
.
What defines an infinite for
statement?
No condition, e.g., for {...}
.
What does break
do in a for
loop?
Exits the loop immediately.
What does continue
do in a for
loop?
Skips to the next iteration.
What does a for-range
statement return?
Index (i
) and value (v
) for each iteration.
How do you ignore a value in a for-range
loop?
Use _
(e.g., for _, v := range items {...}
).
Are map iterations in a for-range
ordered?
No, they’re random for security.
What does a for-range
over a string iterate?
Runes, not bytes.
How can you control an outer for
loop from an inner one?
Use a label, e.g., outer: for {... continue outer
}.
How do you structure a switch statement in Go?
No parentheses around the condition; cases don’t fall through by default.
How do blank switch statements work in Go?
They allow boolean-based conditions instead of comparing against a single value.
When should you use switch
over if
in Go?
Use switch when making multiple related comparisons for clarity.