Scoping and Variable Management
Scoping rules determine where variables are accessible in your program. Harneet uses lexical scoping, meaning the scope of a variable is determined by its position in the source code.
Global Scope
Variables declared outside of any function or block have global scope and are accessible from anywhere in the program.
| Global Scope |
|---|
| package main
import fmt
var global = "accessible everywhere"
function printGlobal() {
fmt.Println(global)
}
printGlobal() // Output: accessible everywhere
|
Local Scope (Function Scope)
Variables declared inside a function have local scope and are only accessible within that function.
| Local Scope |
|---|
| package main
import fmt
function example() {
var local = "only in function"
fmt.Println(local)
}
example() // Output: only in function
// fmt.Println(local) // Error: local is not defined
|
Block Scope
Variables declared inside a block (e.g., if statements, for loops) have block scope and are only accessible within that block.
| Block Scope |
|---|
| package main
import fmt
if true {
var blockScope = "only in this block"
fmt.Println(blockScope) // Output: only in this block
}
// fmt.Println(blockScope) // Error: blockScope is not defined
|
Accessing Outer Scope Variables
Inner scopes can access variables from their outer (enclosing) scopes.
| Nested Scopes |
|---|
| package main
import fmt
var outerVar = "I am from outer scope"
function outer() {
var innerVar = "I am from inner scope"
function nested() {
fmt.Println(outerVar) // Access outerVar from outer scope
fmt.Println(innerVar) // Access innerVar from inner scope
}
nested()
}
outer()
|
Variable Shadowing
If a variable in an inner scope has the same name as a variable in an outer scope, the inner variable "shadows" the outer one within its scope.
| Variable Shadowing |
|---|
| package main
import fmt
var x = 10
function shadowExample() {
var x = 20 // This 'x' shadows the global 'x'
fmt.Println(x) // Output: 20
}
shadowExample()
fmt.Println(x) // Output: 10 (global 'x' is unchanged)
|