Junior — Middle
How to implement query execution control in a SELECT statement in a database?
sobes.tech AI
Answer from AI
In Go, the scope of a variable is determined by its name and the place of declaration. To declare a variable with limited scope inside a class (struct) or module (package), the following approaches are used:
- Inside a function or method: the variable is declared with
varor short declaration:=and is only visible within that function or method. - Inside a package: variables, functions, types with a name starting with a lowercase letter are only visible within the package. If the name starts with an uppercase letter, it is exported and accessible from other packages.
Example:
package mypackage
var packageVar = 10 // visible only within the mypackage
func myFunc() {
var localVar = 5 // visible only inside myFunc
_ = localVar
}
// Exported variable
var ExportedVar = 20 // accessible from other packages
Thus, to limit the scope of a variable within a module, use lowercase names and declare variables outside functions but within the package. For class (struct) fields, visibility is usually controlled by the first letter's case.