

0 / 2 embers
0 / 3000 xp
click for more info
Complete a lesson to start your streak
click for more info
Difficulty: 3
click for more info
Not enough gems
Cost: 6 gems
1: Functions
incomplete
2: Multiple Parameters
incomplete
3: Unit Test Lessons
incomplete
4: Declaration Syntax
incomplete
5: Passing Variables by Value
incomplete
6: Ignoring Return Values
incomplete
7: Named Return Values
incomplete
8: The Benefits of Named Returns
incomplete
9: Explicit Returns
incomplete
10: Early Returns
incomplete
11: Functions As Values
incomplete
12: Anonymous Functions
incomplete
13: Defer
incomplete
14: Block Scope
incomplete
15: Processing Orders
incomplete
16: Closures
incomplete
17: Currying
incomplete
Back
ctrl+,
Next
ctrl+.
This lesson's interactive features are locked, please to keep using them
Unlike Python, Go is not function-scoped, it's block-scoped. Variables declared inside a block are only accessible within that block (and its nested blocks). There's also the package scope. We'll talk about packages later, but for now, you can think of it as the outermost, nearly global scope.
package main
// scoped to the entire "main" package (basically global)
var age = 19
func sendEmail() {
// scoped to the "sendEmail" function
name := "Jon Snow"
for i := 0; i < 5; i++ {
// scoped to the "for" body
email := "[email protected]"
}
}
Blocks are defined by curly braces {}. New blocks are created for:
It's a bit unusual, but occasionally you'll see a plain old explicit block. It exists for no other reason than to create a new scope.
package main
import "fmt"
func main() {
{
age := 19
// this is okay
fmt.Println(age)
}
// this is not okay
// the age variable is out of scope
fmt.Println(age)
}