In Go, scopes tend to begin and end along the lines of curly braces {}
package main
import {
"fmt"
"math/rand"
}
func main() {
var count = 0
for count < 10 { // A new scope begins
var num = rand.Intn(10) + 1
fmt.Println(num)
count++
} // This scope ends
}
Short declaration
var count = 10
count := 10
A condensed countdown: loop.go
var count = 0
for count = 10; count > 0; count-- {
fmt.Println(count)
}
fmt.Println(count) // count remains in scope
short-loop.go
for count := 10; count > 0; count-- {
fmt.Println(count)
} // count is no longer in scope
short-if.go
if num := rand.Intn(3); num == 0 {
fmt.Println("Space Adventures")
} else if num == 1 {
fmt.Println("SpaceX")
} else {
fmt.Println("Virgin Galactic")
} // num is no longer in scope
short-switch.go
switch num := rand.Intn(10); num {
case 0:
fmt.Println("Space Adventures")
case 1:
fmt.Println("SpaceX")
case 2:
fmt.Println("Virgin Galactic")
default:
fmt.Println("Random spaceline #", num)
}