Sobes.tech
Junior — Middle

Is it possible to access a variable declared inside a function from outside its scope?

sobes.tech AI

Answer from AI

In Go, a variable declared inside a function has local scope and is not directly accessible outside that function.

However, you can access the variable's value from outside through closures or by returning the value from the function.

Example with a closure:

func counter() func() int {
    count := 0
    return func() int {
        count++
        return count
    }
}

func main() {
    c := counter()
    fmt.Println(c()) // 1
    fmt.Println(c()) // 2
}

Here, the variable count is declared inside the counter function but is accessible through the returned function.

There is no direct way to access a local variable from outside the function without such techniques.