Scope

Wikipedia: Scope
Tengo uses lexical (block) scoping. := always declares a new variable in the current scope; = assigns to an existing one in an enclosing scope.

fmt := import("fmt")
x := 10
if true {
    x := 20
    fmt.println(x)
}
fmt.println(x)
if true {
    x = 30
}
fmt.println(x)
counter := 0
inc := func() { counter++ }
inc()
inc()
fmt.println(counter)
fns := []
for i := 0; i < 3; i++ {
    fns = append(fns, func() { return i })
}
fmt.printf("%d %d %d\n", fns[0](), fns[1](), fns[2]())
fns2 := []
for i := 0; i < 3; i++ {
    fns2 = append(fns2, (func(v) { return func() { return v } })(i))
}
fmt.printf("%d %d %d\n", fns2[0](), fns2[1](), fns2[2]())

try it

20
10
30
2
3 3 3
0 1 2
loading…