Go Tutorial - Section 2

In the last section, we covered the basics of Go Programming, its structure, syntax and the different data types that it supports. If you feel you need a revision of those topics, go here. In this section, we will cover the next set of topics required for writing a full-fledged program in Go.

  1. Variables.

  2. Constants.

  3. Operators.

  4. Decision Making.


Variables


A Variable is a placeholder of the information which can be changed at runtime. Variables allow to Retrieve and Manipulate the stored information. The name of a variable can be composed of letters, digits, and the underscore character. It must begin with either a letter or an underscore. Upper and lowercase letters are distinct because Go is case-sensitive. In the last section, we have already studied about data types. This is where it comes into usage. A variable is bound to a data type. The data type defines what kind of information can be stored in the variable. Rules for naming a variable:

  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. The name of the variable is case sensitive.

  4. Keywords are not allowed to use as a variable name.

  5. 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.

How do we define a variable?


Go programming language provides us with a couple of ways to declare a variable.


Static Declaration:


A static variable declaration provides assurance to the compiler that there is one variable available with the given type and name so that the compiler can proceed for further compilation without requiring the complete detail of the variable. A variable declaration has its meaning at the time of compilation only, the compiler needs the actual variable declaration at the time of linking of the program.

package main

import "fmt"

func main() {
   var x float64
   x = 20.0
   fmt.Println(x)
   fmt.Printf("x is of type %T\n", x)
}

The above program is an example of a static variable declaration. It uses the syntax:

var variable_name type = expression

Important points to remember while using a static declaration.

  1. 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.

  2. You are allowed to declare multiple variables of the same type in the single declaration.

Dynamic Declaration:

A dynamic type variable declaration requires the compiler to interpret the type of the variable based on the value passed to it. The compiler does not require a variable to have type statically as a necessary requirement.

package main

import "fmt"

func main() {
   var x = 20.0
   y := 42 
   fmt.Println(x)
   fmt.Println(y)
   fmt.Printf("x is of type %T\n", x)
   fmt.Printf("y is of type %T\n", y)	
}

The above example covers the two ways in which dynamic declaration can be done.


Method 1: Using var

var x = 20.0

Method 2: Shorthand method.

y := 42

Important points:

  1. The type of the variable is determined by the value-initialize in the expression.

  2. Most of the local variables are declared and initialized by using short variable declarations due to their brevity and flexibility.

  3. The var declaration of variables are used for those local variables which need an explicit type that differs from the initializer expression, or for those variables whose values are assigned later and the initialized value is unimportant

  4. Using short variable declaration you are allowed to declare multiple variables in the single declaration.

  5. In a short variable declaration, you are allowed to initialize a set of variables by the calling function that returns multiple values.

  6. A short variable declaration acts like an assignment only when for those variables that are already declared in the same lexical block. The variables that are declared in the outer block are ignored.

  7. Using short variable declaration you are allowed to declare multiple variables of different types in the single declaration. The type of these variables is determined by the expression.

Scope of a variable If you notice the point #2 above, I have used a term called local variable. What exactly is a local variable? To understand that, we need to understand a concept called 'variable scope'.


A scope in any programming is a region of the program where a defined variable can exist and beyond that, the variable cannot be accessed.

Like other programming languages, Go provides two scopes for a variable.

  1. Local Scope Variables that are declared inside a function or a block are termed as Local variables. These are not accessible outside the function or block.

  2. Global Scope Global variables are defined outside of a function, usually on top of the program. Global variables hold their value throughout the lifetime of the program and they can be accessed inside any of the functions defined for the program. A global variable can be accessed by any function. That is, a global variable is available for use throughout the program after its declaration.

package main

import "fmt"

var c int
func main() {
   /* local variable declaration */
   var a, b int 

   /* actual initialization */
   a = 10
   b = 20
   c = a + b

   fmt.Printf ("value of a = %d, b = %d and c = %d\n", a, b, c)
}

In the above example, the variables a and b are declared inside the function main which makes them local to that function. It means, if we try to access a and b outside the main function, the compiler will throw an error. Whereas, variable c has been declared outside any function and thus holds a global scope. The variable will be accessible to any function/block in the program.


Constants


Constants refer to fixed values that the program may not alter during its execution. These fixed values are also called literals. There can be any basic data types of constant like an integer constant, a floating constant, a character constant, or a string literal. Constants are declared like variables but in using a const keyword as a prefix to declare constant with a specific type. It cannot be declared using:=syntax. There are three types of constants in Go.

  1. Numeric Constants.

  2. String Constants.

  3. Boolean Constants.

Numeric Constants


Numeric Constants can be further classified into three categories.


Integer Constants:

An integer literal can be a decimal, octal, or hexadecimal constant. A prefix specifies the base or radix: 0x or 0X for hexadecimal, 0 for octal, and nothing for decimal.

An integer literal can also have a suffix that is a combination of U and L, for unsigned and long, respectively. The suffix can be uppercase or lowercase and can be in any order. An int can store at maximum a 64-bit integer, and sometimes less.

Following are the example of integer constants.

85         /* decimal */
0213       /* octal */
0x4b       /* hexadecimal */
30         /* int */
30u        /* unsigned int */
30l        /* long */
30ul       /* unsigned long */
212         /* Legal */
215u        /* Legal */
0xFeeL      /* Legal */
078         /* Illegal: 8 is not an octal digit */
032UU       /* Illegal: cannot repeat a suffix */

Floating-Number Constants:


A floating-point literal has an integer part, a decimal point, a fractional part, and an exponent part. You can represent floating point literals either in decimal form or exponential form. While representing using the decimal form, you must include the decimal point, the exponent, or both. while representing using the exponential form, must include the integer part, the fractional part, or both. Following are the examples of floating-number constants.

3.14159       /* Legal */
314159E-5L    /* Legal */
510E          /* Illegal: incomplete exponent */
210f          /* Illegal: no decimal or exponent */
.e55          /* Illegal: missing integer or fraction */

Complex Constants:


Complex constants behave a lot like floating-point constants. Complex constants have two parts, the first constant is the real part and the second constant is the imaginary part.


Following are a couple of examples of complex constants.

(0.0, 0.0) 
(-123.456E+30, 987.654E-29)

String Constants


String literals or constants are enclosed in double-quotes. A string contains characters that are similar to character literals: plain characters, escape sequences, and universal characters. Strings can be concatenated with + and += operators. String types are all comparable by using operators like==, !=and (for comparing of same types). Following are the examples of String Constants

"hello, world"

"hello, \n

dear"

"hello, " + " w"+"orld"

Boolean Constants


Boolean constants are similar to string constants. It applies the same rules as a string constant. The difference is only that it has two untyped constants true and false.

package main

import "fmt"

const Pi = 3.14

func main() {
 const trueConst = true
    type myBool bool
    var defaultBool = trueConst // allowed
    var customBool myBool = trueConst // allowed  
  //  defaultBool = customBool // not allowed
    fmt.Println(defaultBool)
    fmt.Println(customBool)

    
}

Output:

true
true

Operators


Operators are the foundation of any programming language. Thus the functionality of the Go language is incomplete without the use of operators. Operators allow us to perform different kinds of operations on operands. In Go, operators can be classified under the following categories.

  1. Arithmetic Operators

  2. Relational Operators

  3. Logical Operators

  4. Bitwise Operators

  5. Assignment Operators

  6. Miscellaneous Operators

Arithmetic Operators

Relational Operators

Logical Operators

Bitwise Operators

Assignment Operators

Miscellaneous Operators


Decision Making


Decision making structures require that the programmer specify one or more conditions to be evaluated or tested by the program, along with a statement or statements to be executed if the condition is determined to be true, and optionally, other statements to be executed if the condition is determined to be false. There are 4 kinds of decision-making statements that Go supports.


If Statement


This is the most simple decision-making statement. It is used to decide whether a certain statement or block of statements will be executed or not i.e if a certain condition is true then a block of statement is executed otherwise not. Syntax:

if(condition) {

   // Statements to execute if
   // condition is true
}

Flow Diagram:

If-Else Statement

The if statement alone tells us that if a condition is true it will execute a block of statements and if the condition is false it won’t. But what if we want to do something else if the condition is false. Here comes the else statement. We can use the else statement with if statement to execute a block of code when the condition is false.


Syntax:

if (condition) {

    // Executes this block if
    // condition is true
} else {

    // Executes this block if
    // condition is false
}

Flow Diagram:


Nested If Statement

A nested if is an if statement that is the target of another if or else. Nested if statements mean an if statement inside an if statement.


Syntax:

if (condition1) {

   // Executes when condition1 is true
   
   if (condition2) {

      // Executes when condition2 is true
   }
}

Flow Diagram:

If-Else Ladder

The if statements are executed from the top down. As soon as one of the conditions controlling the if is true, the statement associated with that if is executed, and the rest of the ladder is bypassed. If none of the conditions is true, then the final else statement will be executed.


Syntax:

if(condition_1) {

     // this block will execute 
     // when condition_1 is true

} else if(condition_2) {

    // this block will execute 
    // when condition2 is true
}
.
.
. else {

      // this block will execute when none
     // of the condition is true
}

Flow Diagram:

This brings us to the conclusion of the second section of my go tutorials. Go back and practice the concepts and come back for the third part of the tutorial.


 

+919853340643

©2020 by Aman Sinha.