Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Golang shadowing variable

Tags:

go

Why in this code the variable 'a' is shadowed? I define it in outer scope, then, in the inner scope I have to use the ':=' syntax to assign a new value to it (result from a function call), because I also need to have the 'err' variable, which is new. But this shadows 'a', and later, outside the block, the 'a' returns automatically to the initial value.

package main

import (
    "fmt"
)

func work() {
    a := "outside"

    {
        a, err := foo()
        fmt.Printf("here: %v %v\n", a, err)
    }

    fmt.Printf("but here: %v \n", a)
}

func foo() (string, error) {
    return "inside", fmt.Errorf("WTF?")
}

func main() {
    work()
}

The result is:

here: inside WTF?
but here: outside 

So this forces me to use a new variable in the inner block, e.g. 'b', and then assign 'b' to 'a', like this? This would be stupid, wouldn't it? I feel like I am missing something here. Please help.

func work() {
    a := "outside"

    {
        b, err := foo()
        a = b // I DON'T WANT THIS !!!
        fmt.Printf("here: %v %v\n", a, err)
    }

    fmt.Printf("but here: %v \n", a)
}

like image 812
YotKay Avatar asked Nov 05 '25 02:11

YotKay


2 Answers

You are using short-form variable declaration, which will redeclare the variables in the outer scope, and thus, shadowing them. You can simply declare the error variable, and use regular assignment

func work() {
    a := "outside"

    {
        var err error
        a, err = foo() // No shadowing
    }

    fmt.Printf("but here: %v \n", a)
}
like image 165
Burak Serdar Avatar answered Nov 09 '25 05:11

Burak Serdar


Shadowing occurs in Go when a variable declared in a nested scope has the same name as a variable declared in an outer scope. In such cases, the variable in the inner scope shadows or hides the variable in the outer scope.

Example:

func main() {
    x := 10
    fmt.Println("Outer x:", x) // Outer x: 10

    {
        x := 20
        fmt.Println("Inner x:", x) // Inner x: 20
    }

    fmt.Println("Outer x:", x) // Outer x: 10
}
like image 35
Mubashir Qadeer Avatar answered Nov 09 '25 04:11

Mubashir Qadeer



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!