What is shadowing in Go language?

Go | Shadowing: In this tutorial, we are going to learn about shadowing, its usages, and examples.
Submitted by IncludeHelp, on October 01, 2021

In the Go programming language (even in other programming languages also), the variable shadowing occurs when a variable declared within a certain scope such as decision block, method, or inner class has the same name as a variable declared in an outer scope.

Example of Variable Shadowing

Consider the below example,

// Go program to demonstrate the example
// of variable shadowing

package main

import (
	"fmt"
)

func main() {
	x := 0

	// Print the value
	fmt.Println("Before the decision block, x:", x)

	if true {
		x := 1
		x++
	}

	// Print the value
	fmt.Println("After the decision block, x:", x)
}

Output:

Before the decision block, x: 0
After the decision block, x: 0

In the above program, the statement x := 1 declares a new variable which shadows the original x throughout the scope of the if statement. So, this variable (x) declared within the if statement is known as shadow variable.

If we want to reuse the actual variable x from the outer block, then within the if statement, write x = 1 instead.

package main

import (
	"fmt"
)

func main() {
	x := 0

	// Print the value
	fmt.Println("Before the decision block, x:", x)

	if true {
		x = 1
		x++
	}

	// Print the value
	fmt.Println("After the decision block, x:", x)
}

Output:

Before the decision block, x: 0
After the decision block, x: 2

Golang FAQ »




Comments and Discussions!

Load comments ↻






Copyright © 2024 www.includehelp.com. All rights reserved.