Variable Scope in Golang 1.20
In this video we are going to generate source code for the GoLang Program, Variable Scope using chatGPT.
After generating we will verify and run the generated code.
IMPORTANT NOTE on SOURCE CODE: only source code that are acceptable by the youtube description box will be displayed.
##############SOURCE CODE#########################
package main
import "fmt"
// Declaring a global variable
var globalVar int = 10
func main() {
// Declaring a local variable
var localVar int = 20
// Printing the values of the global and local variables
fmt.Println("Global variable:", globalVar)
fmt.Println("Local variable:", localVar)
// Changing the values of the global and local variables
globalVar = 30
localVar = 40
// Printing the updated values of the global and local variables
fmt.Println("Global variable after update:", globalVar)
fmt.Println("Local variable after update:", localVar)
// Calling a function that declares and modifies a local variable
modifyLocalVar()
}
func modifyLocalVar() {
// Declaring a local variable
var localVar int = 50
// Printing the value of the local variable
fmt.Println("Local variable inside modifyLocalVar:", localVar)
// Changing the value of the local variable
localVar = 60
// Printing the updated value of the local variable
fmt.Println("Local variable inside modifyLocalVar after update:", localVar)
}
##############END OF SOURCE CODE#########################
Below is the explanation for the program:
In this program, we are demonstrating the scope of variables in Go. We declare two variables: globalVar and localVar.
globalVar is declared outside of any function and is therefore a global variable. It can be accessed and modified from any function in the program.
localVar is declared inside the main() function and is therefore a local variable. It can only be accessed and modified within the main() function.
We print the values of both variables using fmt.Println() statements, then modify their values and print them again to show how their values change.
We also call a function modifyLocalVar() that declares and modifies a local variable with the same name as the localVar variable in main(). This demonstrates that variables with the same name can be declared in different functions without causing conflicts, because they have different scopes.
Global variable: 10
Local variable: 20
Global variable after update: 30
Local variable after update: 40
Local variable inside modifyLocalVar: 50
Local variable inside modifyLocalVar after update: 60
As you can see, the scope of a variable determines where it can be accessed and modified within a program. Global variables can be accessed and modified from anywhere in the program, while local variables can only be accessed and modified within the function in which they are declared.
#go #goprogramming #golang #golangtutorial #golanguage