How can a variable with limited scope be declared inside a class or module?
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 (structure) or module (package), the following approaches are used:
-
Inside a function or method: the variable is declared using
varor short declaration:=and is visible only within that function or method. -
Inside a package: variables, functions, and types with names starting with a lowercase letter are visible only within the package (module). 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 package
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, you should use names starting with a lowercase letter and declare variables outside functions but within the package. To restrict visibility inside a class (structure), usually, fields of the structure are used, where visibility is also determined by the case of the first letter.