Variable Naming & Scope of Variable

Rules for Creating the variable name

  1. Variable name can contain Alphabets (A-Z/a-z), Digits (0-9) and Underscore( _ ).
  2. A variable name must start with alphabet or underscore.
  3. Spaces and special systems are not allowed.
  4. Reserved words are not allowed as a variable name.
  5. A variable name should be meaningful.
  6. Go is case sensitive language so age, Age, AGE all are treated as a different variable.

Some correct variable names

  1. name
  2. father_name
  3. fatherName
  4. __AGE
  5. number1
  6. car_modal_name
  7. is_verified
  8. intnum

Some incorrect variable names

  1. father's_name
  2. father#name
  3. 2persons
  4. 0007
  5. 000Name
  6. int
  7. a#b

Note

There are two popular ways to create multi-word variables.
  1. player_name: Each word is separated by an underscore
  2. 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

  1. Global variables are accessible to multiple function and across file also, once declared.
  2. A global variable is generally declared outside the function.
  3. 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

Popular posts from this blog

Overview of Go lang

Arrays in C Language

Program to calculate telephone bill

String in golang

Data Types in Go language

Installing go lang

Say Hello world in Go lang

Creating your first html page

Arrays in Go lang

Decision Making in Go lang