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.
Let’s begin with understanding the need for variables in a programming language,
Consider the below Simple executable Go language 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.
NOTE: A shared library package is used to build reusable codes whereas packaging main for developing executable codes.
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 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 the 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.
Variables are special containers that are capable of storing a value and the value remains fixed during the execution of the program.
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.
Golang //valid variable name
_golang //valid variable name
Golang236,golang_0 //valid variable name
236golang //invalid varaible name
236golang //invalid variable name
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 |
Variables in Go is declared mainly using
The var keyword is used with two different methods to declare variables
Two-step declaration using var keyword followed by variable name and its type. Then initializes the variable value to a variable declared.
Syntax
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.
One of the simple declaration methods, the syntax follows a var keyword with a variable name, and a value is assigned to it.
Syntax
var <variable_name> = <value>
var price = 35
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.
Syntax
<variable_name> := <value>
Price := 35
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:
|
Allows only single-line declaration and assignment of values Eg:
|
Declaration and assignment of values to variables can be done separately | cannot be done separately |
This Go program is an example of 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
Declaration of short variables outside a function results in compilation error. Variables cannot be declared and assigned outside a function using “:=”.
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 “:=”
In Golang, the values to each variable present in the go program can be initialized at the beginning of the program itself if the values to be stored or contained by each variable are already known or predefined.
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.
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
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
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)
}
Output:
0 false
Explanation
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.
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 SamsungSo far we discussed about different types of declarations in Go program. The simple program given below is a compositiin of thesev 3 diffrent types of declaration with 2 var statements and 1 short hand ":=" declaration.
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 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
)
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
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
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
The variables are categorized into three types based on their name and storage location.
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:
380 cat 87
Explanation
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.
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": "&"}