Variables in Go language

In this  Go language tutorial also depicted as  Go or  Golang,  you will learn all about
the core of all programming languages known as variables, the basic unit of programming language. We will discuss in detail what are variables, how to declare and define variables in Golang followed by understanding the scope and lifetime of variables, their naming conventions, and how variables get shadowed in Golang.

Concept of variables 

Let’s begin with understanding the need for variables in a programming language,
Consider the below Simple executable Go language program

Go Program


package main            //Declaration of main package 

import "fmt" //Importing input-output libraries

func main() {          //Main function

 fmt.Println("Hello Users")    //Display print statement
}

Output:


Hello Users

This executable Golang program contains 4 different parts. Let us discuss these lines of codes in brief for a greater understanding of the variable concept.

  •  Package main   :package main is the package declaration with which every program starts its execution. The package main initializes the program execution by telling the Go compiler that instead of using a shared library the programs must be executed as executable codes.

    NOTE: A shared library package is used to build reusable codes whereas packaging main for developing executable codes.

  • Import “fmt”: The second line code import “fmt”.Imports fmt package file responsible for the implementation of I/O methods or functions
  • Func main() :The main function with func keyword followed by curly brackets {}. Programming code written inside the curly brackets begins its execution from this point. In simple words, the entry point where the program execution starts.
  • fmt.Println():Println() is a function that prints specified text provided within double quotes on the screen which is imported from the fmt package in Go language to display output to the user in the console. The fmt.Println() function displays “Hello Users” as output in the console.

For better understanding let’s have a look at the screenshot below for the same program (Example 1). Created a file called simple. go and add the above-given lines of codes.

GO - Variables

Run Go program using command

go run simple. go

In the console prints(displays) output as

Output:


Hello Users

The execution of the same program multiple times results in printing the same result as output. The print statement remains fixed which cannot be changed during the execution of the program. It is impossible to solve a real-world scenario with fixed values so there needs to be some mechanism that must be capable of storing the values that are read from the user. It should also satisfy the requirement of changing the values stored when the program is in execution. So this is why we had the concept of variables.

What are variables?

Variables are special containers that are capable of storing a value and the value remains fixed during the execution of the program.

Why declaration is needed in Golang

Declaration specifies the variable name and variable type used in the Go program. Like other languages C, C++, Java Go is also a statically typed programming language. Go programming language is a statically typed programming language in which the variables are declared before being used during the execution of the program.

Naming Convention and styles in Golang

  • Variable names only contain the letters ‘a-z’ or ’A-Z’ or digits 0-9 as well as the character underscore  ‘_ ’.
    Golang     //valid variable name
    _golang     //valid variable name
    Golang236,golang_0   //valid variable name
    236golang   //invalid varaible name
    
  • Variable names must begin with a letter or an underscore (_) and should not start with a digit.
    236golang     //invalid variable name
    
  • The name of the variable is case-sensitive.
  • Keywords are not allowed to use as a variable name
  • There is no limit on the length of the name of the variable, but it is advisable to use an optimum length of 4 – 15 letters only.
  • Variable styles use mixedCaps or MixedCaps 

    Consider emp_details in which employee name can be represented as either emp_Name or Emp_Name

    Example  : var emp_Name = “john” Emp_Name := “Stephen”

    Program to understand the example

    
    package main
    import ("fmt")
    
    func main() {
      var emp_Name string = "John" //Variable in mixedCaps
     
      Emp_Name:= "Stephen" //Variable in MixedCaps
    
      fmt.Println("The variable name in mixedCaps : ",emp_Name)
     
      fmt.Println("The variable name in MixedCaps : ",Emp_Name)
    }
    
     
    

    Output:

    
    The variable name  in mixedCaps :  John
    The variable  name in MixedCaps :  Stephen
    

Note: Avoid using similar variable names within a program

Let’s consider a table for a better understanding of naming rules & styles

INVALID VALID Why not valid?
1Golang Golang1 Don’t start with a digit
%Golang Golang Don’t start with the symbol
Go  lang Golang No space permitted
Go-lang Golang No hyphens are allowed

Declaration Methods in Golang

Variables in Go is declared mainly using 

  1.     Using the ‘var’ keyword 
  2.     Short variable declaration using “ : = “ .

Declaring a variable with var keyword in Golang

The var keyword is used with two different methods to declare variables

  1. Two-step declaration using var keyword followed by variable name and its type. Then initializes the variable value to a variable declared.

    
    var <variable_name> <type>
    <variable_name> =  <value>
    
    
    
    var  price int
    price = 35 
    
    

    The keyword var followed by the variable price of type integer is declared. In the next line, a value of 35 is assigned to the variable price. Thus the variable price holds a value of 35 during the program execution time.

  2. One of the simple declaration methods, the syntax follows a var keyword with a variable name, and a value is assigned to it.

    
    var <variable_name> = <value>
    
    
    
    var price = 35
    
    

Declaring variable using the colon-equals assignment operator (:=)

The local variables are declared and initialized in the functions using short variable declaration. In “:= “ variable declaration the type of variable is inferred by the compiler from the assigned or stored value to the variable.


<variable_name> := <value>


Price := 35

Usage of Var keyword and short variable declaration

var keyword :=
var  used inside and outside of the main function Used only inside the main function
Var syntax allows variable declaration & value assignment in single or different lines. single-line Eg:
var name1 string = “Golang”
   
Separate line Eg:
var name1 string
name1=” Golang”

 

Allows only single-line declaration and assignment of values Eg:
name1:= “Golang”

 

Declaration and assignment of values to variables can be done separately cannot be done separately

var keyword inside and outside a function

This Go program is an example for variable declaration both inside and outside of a function using the var keyword


package main
import ("fmt")
/* variable declared outside function */
var name1 string
/* variables declared and assigned values outside function */
var num int = 2021   
var c = 3

func main() {
/* variable name1 declared outside function assigned value inside function */
  name1 = "Golang"   
  fmt.Println(name1)
  fmt.Println(num)
  fmt.Println(c)
}

Output:


Golang
2021
3

Short variable declaration outside a function

Declaration of short variables outside a function results in compilation error. Variables cannot be declared and assigned outside a function using “:=”.

Example


package main
import ("fmt")
 
name1 := "Golang"    //short variable declaration
 
func main() {
  fmt.Println(name1)  //Type inferred as string
}

Output:


-/home/5ZqYyz
prog.go:4:1 Syntax error non-declaration statement outside function body

Note: Variables cannot be declared and assigned outside a function using “:=”

Initialized Variable Declaration

In Golang variables are declared by initial values if values stored by variables in the program are known prior.

Example


package main

import "fmt"

func main() {
  var price_ph //var keyword
                    //variable  price_phone
                    //value 15000

 var mobile_name  = "SAMSUNG" //var keyword,variable phone
     //value string type SAMSUNG
 Ear_phone := 300             // := assigns 300 to variable Ear_phone

 fmt.Println("Prints phone prices by inferring its type", price_phone)
 fmt.Println("Displays name of phone ", phone)
 fmt.Println("Displays price of Ear_phone", Ear_phone)
}


In these lines of codes, all variables are initialized with some type of values to later use in the Go program.This is a brief idea of how variables with values are initialized or used in a Go language.

  • var price_ph line assigns value 15000 of integer type to variable price_phone declared using the var keyword.
  • var mobile_name = "SAMSUNG", this line assigns value Samsung in uppercase letters of type string to the variable mobile_name using the var keyword.
  • Ear_phone := 300  ,colons-equal assignment operator assigns integer type value 300 to variable named Ear_phone.

Output:


Prints phone prices by inferring its type : 15000
Displays name of phone : SAMSUNG
Displays price of ear_phone :300

Note: The type of values are inferred from their values

Default values of Uninitialized Variable Declaration

In Go uninitialized variables, that is if a variable is not declared with an initial value, the variable will initialize a default value of its declared type. Once a variable is declared it is allocated with a Zero value matching to its built-in type. The zero values or default values of variables is explained below with an example

Example


package main
import ("fmt")

func main() {

  var words string    //default value set to string
  var number int  //default value set to integer
  var Logic_gates bool //default value set to boolean

  fmt.Println(words)
  fmt.Println(number)
  fmt.Println(Logic_gates)
}

Explanation

  • The  lines in the code given below are variables without any initial values
    • var words string
    • var number int
    • var Logic_gates bool
  • There are three variables namely, words, number,logic_gates each are specified with its type such as string, integer, boolean respectively.
  • The variables are not initialized with any values but while compiling the code default values (zero values) of corresponding types are assigned to the variable.
  • This is how default values are set when no initial values are set with variables.
  • After successful compilation of code, default values are assigned with respective types
    • Words as “ ”
    • number as 0
    • Logic_gates as false

Example


package main

import ("fmt")

func main() {

  var words string    //default value set to string
  var number int  //default value set to integer
  var Logic_gates bool //default value set to boolean

  fmt.Println(words)
  fmt.Println(number)

Output:


0
false

Assigning variable value after the declaration

In case the value of the variable is unknown it is possible to assign a value to the variable after it is declared in the program.

Consider the syntax 

var <varaiable_name><type>
<variable_name> = <value>

Using this syntax, a variable can be assigned a value after the variable declaration.

Example Program for  Assigning variable value after the declaration


package main
import ("fmt")

func main() {

  var mobile_name string           // variable phone of string type 
  mobile_name = "SAMSUNG"          // variable phone reads value samsung
  fmt.Println(mobile_name )         //Displays value as output
}

Output:

SAMSUNG

In this program, the variables are declared first with their type by the programmer. In the next line, only the value is assigned to the variable.

  • var mobile_name string   :  A variable mobile_name of string type is declared.
  • mobile_name = "SAMSUNG" :  A variable mobile_name reads value Samsung

Simple Go program with different types of declaration

A Go program comprised of different types of declarations discussed so far is given below:

Program


package main
import "fmt"
func main() {
 
 //method 1
 var value1 int
 value1 = 380

 //method 2
 var value2 = "cat"

 //method 3
 value3 := 87

 fmt.Println(value1, value2, value3)
}

The three different syntaxes for declaring and defining variables mentioned as method1,method2, method3 are understood from the above program.

Output:

 

Multiple variable declaration definition

Multiple variables in the Go program are defined using another shorthand. Keyword var followed by parenthesis used to define variables at different code lines in the Go program.


var (
x=100
y=” hello”
z=0
)

Program


package main
import ("fmt")
func main() {
/* Multiple variable declaration*/
  var(
   x=100
 y= "hello"
 z=0  )
  fmt.Println(x,y,z)         //Displays value as output
}

Output:

100 hello 0

Multiple Assignment of variables

Go programming language enables users or programmers to assign multiple values to different variables within the same line. Variables in a single line can have values of different data types

Program


package main
import ("fmt")

func main(){
 
num1, num2, num3 := "one", 2, "three"  //Multiple variable assignment

fmt.Println(num1)
fmt.Println(num2)
fmt.Println(num3)

}

Output:

one
2
three

In this Go example, Num1,num2,num3 are three variables declared in a single line. Each variable is of different data types

  • num1 is a string type
  • num2 is an integer type
  • num3 is a string type

Scope and Lifetime of a variable

The variables are categorized into three types based on their name and storage location.

  •     Local variables: variables declared inside a function
  •     Global variables: Variables declared outside a function and the name of the variable should begin with upper case letters.
  •     Package level variables: Variables declared outside a function and the name of the variable should begin with lower case letters.
     

Lets’s understand with an example


package main
import "fmt"

/*Global variables can be  accessed by all
the  functions in the same or different packages
*/

var Global_var int  //Begins with uppercase letter

/*Package level variables only accessed
from the function of the same package
*/

var pack_var int   //begins with lowercase letter

func main() {
 /* Local variables cannot be accessed
 from outside of the function
 */

 //method 1
 var value1 int
 value1 = 380

 //method 2
 var value2 = "cat"

 //method 3
 value3 := 87

 fmt.Println(value1, value2, value3)
}

Output:

 

Explanation

  • In the above-given program, three variables are declared within the main function. So variables value1,value2,value3 are local variables that can be accessed only from the main function. Other functions in the program are restricted to access the local variables.
  • The program declares var pack_var = int,pack_var is another variable that starts with a lower case letter and is declared outside the main function forms a package level variable.
  • Similarly, a variable Global_var is declared with starting letter as uppercase, the syntax used is var Global_var = int which is further accessible by other functions in a Go program known as Global variable.
     

Note:

1. At the package level, variable:= syntax is not allowed to declare a variable if do so a compilation error will occur.

2. Once a variable is declared and not used anywhere in the Go program results in a compilation error.
 

Shadowing

Suppose a variable declared in package level is redeclared as a local variable. While trying to access the local variable, the package level variable gets shadowed by the local variable.
Consider the Go program


Package main
import "fmt"

var value0 = 0   //package level variable

func main() {
 var value0 = 34  //local variable
 fmt.Println(value0)

}

Output:

34

value0 is a variable initialized with two values, one as a package level variable using syntax followed by a var keyword, that assigns 0 to value0. The same variable value0 is redeclared inside the main function as a local variable which stores a value 34. While the program is in execution the local variable is only considered for execution thus the shadowing concept works. Variables are not limited to data types like strings, integers, and booleans. Variables can be represented with some other data types as given below which will be discussed in the next tutorial.


s := "Hello, World!"
f := 465.86
b := 15 > 9 // A Boolean value will return either true or false
array := [3]string{"item_1", "item_2", "item_3"}
slice := []string{"one", "two", "three"}
m := map[string]string{"letter": "h", "number": "nine", "symbol": "&"}