Variable scope in Go
There are only three levels of variable scope in Go: package level, globe level and block level.
Package Level:
Package level variables are accessible inside the package. They are defined directly on the package level and started with lower case. For example:
package main
import "fmt"
var counter int = 42
func main() {
fmt.Println(counter);
}
Globe Level:
Globe level variables can be accessed outside of the package. Similar to package level variables, they are also defined directly on the package level, however they must be started in upper case. For example:
package main
import "fmt"
var Counter int = 42 //Here Counter is accessible outside of the package
func main() {
fmt.Println(Counter);
}
Globe level variables can be accessed by other packages using packagename.VariableName after import the package.
Block Level:
Block level is like local variables in other programming languages. They are defined in a block like functions, if statement or else.
package main
import "fmt"
func main() {
counter := 42
fmt.Println(counter);
}
Comments
Post a Comment