Variables in Go

  • Variable is a placeholder of the information which can be changed at runtime. Variables allow to Retrieve and Manipulate the stored information.
    1. Variable names must begin with a letter or an underscore(). And the names may contain the letters ‘a-z’ or ’A-Z’ or digits 0-9 as well as the character ‘’.
    2. A variable name should not start with a digit.
    3. Keywords is not allowed to use as a variable name.

Declaring a Variable

Using var keyword `var variablename type = expression In the above syntax, either _type or = expression can be omitted, but not both.

note : If the expression is removed, then the variable holds zero-value for the type like zero for the number, false for Booleans, “” for strings, and nil for interface and reference type. So, there is ==no such concept of an uninitialized variable in Go language.==

Using short variable declaration `variable_name:= expression The local variables which are initialized in the functions are declared by using short variable declaration ( := ).

package main
 
import "fmt"
 
func main() {
 
// Using short variable declaration
// Multiple variables of same types
// are declared and initialized in 
// the single line
 
myvar1, myvar2, myvar3 := 800, 34, 56
 
fmt.println( myvar1 , myvar2 , myvar3)
 
}

Constants

Once the value of constant is defined, it cannot be modified further. Constants are declared like variables but in using a const keyword as a prefix to declare a constant with a specific type. It cannot be declared using “:=” syntax.

package main
 
import "fmt"
 
const PI = 3.14
 
func main(){
 
const A = 10
fmt.println("The value of A is ",a)
fmt.println(PI)
}