57. Go - Scopes

Package Level Scope:
- declaring variables outside main function.
- variables are accessible within other scripts within same package (folder)

Block Level Scope:
- declaring variables inside function curly braces

Exported and NotExported Names:
- Lower case variables/names are not accessible outside of package.
- Upper case variables/names are exported names and can be accessed outside of package.

Return Function with inner closure scope:

package main

import "fmt"

func printerr() func() int {
    x := 0

    return func() int {
        x++
        return x
    }
}

func main() {
    test1 := printerr()
    fmt.Println(test1())
    test2 := printerr()
    fmt.Println(test2())

    fmt.Println("TWO")
    fmt.Println(test2())
    fmt.Println(test2())
    fmt.Println(test2())
    fmt.Println(test2())

    fmt.Println("ONE")
    fmt.Println(test1())

}

// test1 is a printerr function with its own scope of x variable.

// test2 cannot access test1's variable x

Comments

Popular posts from this blog

2. FreeCodeCamp - Dynamic Programming - Learn to Solve Algorithmic Problems & Coding Challenges

20. Data Analytics - Analyze Data to Answer Questions - Week 1

3. Algorithms - Selection Sort