Junior — Middle
How is the scope of variables and functions determined in the Go language?
sobes.tech AI
Answer from AI
In Go, the scope of variables and functions is determined by their declaration location and the export rule:
- Local scope: variables declared inside a function or block are only visible within that block.
- Package scope: variables, functions, and types declared at the package level (outside functions) are visible in all files of that package.
- Exported identifiers: if the name of a variable, function, or type starts with an uppercase letter, it is exported and accessible from other packages.
Example:
package example
var packageVar = 42 // accessible throughout the package
var ExportedVar = 100 // accessible from other packages
func exampleFunc() {
var localVar = "hello" // visible only inside exampleFunc
fmt.Println(localVar)
}
Thus, in Go, scope is closely related to the level of declaration and the case of the first letter of the name.