Google News
logo
Golang - Interview Questions
What do you understand by Shadowing in Golang?
Shadowing is a principle when a variable overrides a variable in a more specific scope. This means that when a variable is declared in an inner scope having the same data type and name in the outer scope, the variable is said to be shadowed. The outer variable is declared before the shadowed variable.
 
Consider a code snippet as shown below :
var numOfCars = 2    // Line 1
type Car struct{
	name string
	model string
	color string
}
cars:= [{
            name:"Toyota",
            model:"Corolla",
            color:"red"
        },
        {
	    name:"Toyota",
            model:"Innova",
            color:"gray"
	}]

func countRedCars(){
    for i:=0; i<numOfCars; i++{
	if cars[i].color == "red" {
		numOfCars +=1    // Line 2
		fmt.Println("Inside countRedCars method ", numOfCars)    //Line 3
	}
    }	    
}
Here, we have a function called countRedCars where we will be counting the red cars. We have the numOfCars variable defined at the beginning indicated by the Line 1  comment. Inside the countRedCars method, we have an if statement that checks whether the colour is red and if red then increments the numOfCars by 1. The interesting point here is that the value of the numCars variable after the end of the if statement will not be affecting the value of the numOfCars variable in the outer scope.
Advertisement