Variable Naming & Scope of Variable
Rules for Creating the variable name
- Variable name can contain Alphabets (A-Z/a-z), Digits (0-9) and Underscore( _ ).
- A variable name must start with alphabet or underscore.
- Spaces and special systems are not allowed.
- Reserved words are not allowed as a variable name.
- A variable name should be meaningful.
- Go is case sensitive language so age, Age, AGE all are treated as a different variable.
Some correct variable names
- name
- father_name
- fatherName
- __AGE
- number1
- car_modal_name
- is_verified
- intnum
Some incorrect variable names
- father's_name
- father#name
- 2persons
- 0007
- 000Name
- int
- a#b
Note
There are two popular ways to create multi-word variables.
- player_name: Each word is separated by an underscore
- playerName: camel case, the first word is in small and from second word first letter of each word is capitalized.
Variable Scope
Scope is the range of places where a variable is allowed to be used is called variable scope.Variable Scope can be of two types
Local variables
Local variables are those which are allowed to be used within the block in which they are defined.
func main( ) {
var isVisible boolean = true
if isVisible {
var name string = "Max"
fmt.Println(name)
}
fmt.Println(isVisible)
// fmt.Println(name) //undefined variable: name
}
- As shown in the above program snippet, two variable isVisible and name is created, but as you can see the name is created within the if block, so it is only accessible within the if block outside the if block name is not accessible. so it produces an error while access outside the if block.
- Local variable automatically deletes from memory when the scope ends.
Global Variable
- Global variables are accessible to multiple function and across file also, once declared.
- A global variable is generally declared outside the function.
- Because the global variable is accessed and modified by multiple functions, so need to be handled with extra care.
var name = "Max"
func f() {
fmt.Println(name)
}
func main() {
f()
fmt.Println(name)
}
- In the above program, the snippet variable name is declared outside the function so it is accessible by all the function inside the file.
Comments