Saturday 28 August 2021

Go for range construct

 The for range construct is useful in many context. It can be used to traverse every item in a collection. It is similar to foreach in other languages. But, we still have the index at each iteration in for range construct.

Syntax:

  1. for ix, val := range coll { }  

Go For Range Example

  1. import "fmt"  
  2. func main() {  
  3.    nums := []int{234}  
  4.    sum := 0  
  5.    for _, value := range nums {// "_ " is to ignore the index  
  6.       sum += value  
  7.    }  
  8.    fmt.Println("sum:", sum)  
  9.    for i, num := range nums {  
  10.       if num == 3 {  
  11.          fmt.Println("index:", I)  
  12.       }  
  13.    }  
  14.    kvs := map[string]string{"1":"mango","2":"apple","3":"banana"}  
  15.    for k, v := range kvs {  
  16.       fmt.Printf("%s -> %s\n", k, v)  
  17.    }      
  18.    for k := range kvs {  
  19.       fmt.Println("key:", k)  
  20.    }  
  21.    for i, c := range "Hi" {  
  22.       fmt.Println(i, c)  
  23.    }  
  24. }  

Output:

sum: 60
1 -> mango
2 -> apple
3 -> banana
key: 1
key: 2
key: 3
0 72
1 105

Go For Loops

 The for loop loops through a block of code a specified number of times.

The for loop is the only loop available in Go.


Go for Loop

Loops are handy if you want to run the same code over and over again, each time with a different value.

Each execution of a loop is called an iteration.

The for loop can take up to three statements:

Syntax

for statement1; statement2; statement3 {
   // code to be executed for each iteration
}

statement1 Initializes the loop counter value.

statement2 Evaluated for each loop iteration. If it evaluates to TRUE, the loop continues. If it evaluates to FALSE, the loop ends.

statement3 Increases the loop counter value.

Note: These statements don't need to be present as loops arguments. However, they need to be present in the code in some form.


for Loop Examples

Example 1

This example will print the numbers from 0 to 4:  

package main
import ("fmt")

func main() {
  for i:=0; i < 5; i++ {
    fmt.Println(i)
  }
}

Result:

0
1
2
3
4

Example 1 explained

  • i:=0; - Initialize the loop counter (i), and set the start value to 0
  • i < 5; - Continue the loop as long as i is less than 5
  • i++ - Increase the loop counter value by 1 for each iteration

Example 2

This example counts to 100 by tens: 

package main
import ("fmt")

func main() {
  for i:=0; i <= 100; i+=10 {
    fmt.Println(i)
  }
}

Result:

0
10
20
30
40
50
60
70
80
90
100

Example 2 explained

  • i:=0; - Initialize the loop counter (i), and set the start value to 0
  • i <= 100; - Continue the loop as long as i is less than or equal to 100
  • i+=10 - Increase the loop counter value by 10 for each iteration

The continue Statement

The continue statement is used to skip one or more iterations in the loop. It then continues with the next iteration in the loop.

Example

This example skips the value of 3:

package main
import ("fmt")

func main() {
&  for i:=0; i < 5; i++ {
    if i == 3 {
      continue
    }
   fmt.Println(i)
  }
}

Result:

0
1
2
4


The break Statement

The break statement is used to break/terminate the loop execution.

Example

This example breaks out of the loop when i is equal to 3:

package main
import ("fmt")

func main() {
  for i:=0; i < 5; i++ {
    if i == 3 {
      break
    }
   fmt.Println(i)
  }
}

Result:

0
1
2

Note: continue and break are usually used with conditions.


Nested Loops

It is possible to place a loop inside another loop.

Here, the "inner loop" will be executed one time for each iteration of the "outer loop":

Example

package main
import ("fmt")

func main() {
  adj := [2]string{"big""tasty"}
  fruits := [3]string{"apple""orange""banana"}
  for i:=0; i < len(adj); i++ {
    for j:=0; j < len(fruits); j++ {
      fmt.Println(adj[i],fruits[j])
    }
  }
}

Result:

big apple
big orange
big banana
tasty apple
tasty orange
tasty banana


The Range Keyword

The range keyword is used to more easily iterate over an array, slice or map. It returns both the index and the value.

The range keyword is used like this:

Syntax

for index, value := array|slice|map {
   // code to be executed for each iteration
}

Example

This example uses range to iterate over an array and print both the indexes and the values at each (idx stores the index, val stores the value):

package main
import ("fmt")

func main() {
  fruits := [3]string{"apple""orange""banana"}
  for idx, val := range fruits {
     fmt.Printf("%v\t%v\n", idx, val)
  }
}

Result:

0      apple
1      orange
2      banana

Tip: To only show the value or the index, you can omit the other output using an underscore (_).

Example

Here, we want to omit the indexes (idx stores the index, val stores the value):

package main
import ("fmt")

func main() {
  fruits := [3]string{"apple""orange""banana"}
  for _, val := range fruits {
     fmt.Printf("%v\n", val)
  }
}

Result:

apple
orange
banana

Example

Here, we want to omit the values (idx stores the index, val stores the value):

package main
import ("fmt")

func main() {
  fruits := [3]string{"apple""orange""banana"}

  for idx, _ := range fruits {
     fmt.Printf("%v\n", idx)
  }
}

Result:

0
1
2

What is Go Language switch?

 The Go switch statement executes one statement from multiple conditions. It is similar to if-else-if chain statement.

Syntax:

  1. switch  var1 {  
  2. case val1:  
  3. .....  
  4. case val2  
  5. .....  
  6. default:  
  7. .....  
  8. }  

The switch statement in Go is more flexible. In the above syntax, var1 is a variable which can be of any type, and val1, val2, ... are possible values of var1.

In switch statement, more than one values can be tested in a case, the values are presented in a comma separated list

like: case val1, val2, val3:

If any case is matched, the corresponding case statement is executed. Here, the break keyword is implicit. So automatic fall-through is not the default behavior in Go switch statement.

For fall-through in Go switch statement, use the keyword "fallthrough" at the end of the branch.

Go Switch Example:

  1. package main  
  2. import "fmt"  
  3. func main() {  
  4.    fmt.Print("Enter Number: ")  
  5.   var input int  
  6.   fmt.Scanln(&input)  
  7.    switch (input) {  
  8.   case 10:  
  9.       fmt.Print("the value is 10")  
  10.     case 20:  
  11.       fmt.Print("the value is 20")  
  12.     case 30:  
  13.       fmt.Print("the value is 30")  
  14.     case 40:  
  15.       fmt.Print("the value is 40")  
  16.     default:  
  17.       fmt.Print(" It is not 10,20,30,40 ")  
  18.    }  
  19. }  

Output:

Enter Number: 20
the value is 20

or

Output:

Enter Number: 35
 It is not 10,20,30,40

Go switch fallthrough example

  1. import "fmt"  
  2. func main() {  
  3.    k := 30  
  4.    switch k {  
  5.    case 10:  
  6.       fmt.Println("was <= 10"); fallthrough;  
  7.    case 20:  
  8.       fmt.Println("was <= 20"); fallthrough;  
  9.    case 30:  
  10.       fmt.Println("was <= 30"); fallthrough;  
  11.    case 40:  
  12.       fmt.Println("was <= 40"); fallthrough;  
  13.    case 50:  
  14.       fmt.Println("was <= 50"); fallthrough;  
  15.    case 60:  
  16.       fmt.Println("was <= 60"); fallthrough;  
  17.    default:  
  18.       fmt.Println("default case")  
  19.    }  
  20. }  

Output:

was <= 30
was <= 40
was <= 50
was <= 60
default case


Go If

 The if statement in Go is used to test the condition. If it evaluates to true, the body of the statement is executed. If it evaluates to false, if block is skipped.

Syntax :

  1. if(boolean_expression) {  
  2.    /* statement(s) got executed only if the expression results in true */  
  3. }  

Go if example

  1. package main  
  2. import "fmt"  
  3. func main() {  
  4.    /* local variable definition */  
  5.    var a int = 10  
  6.    /* check the boolean condition using if statement */  
  7.    if( a % 2==0 ) {      /* if condition is true then print the following 
  8. */ fmt.Printf("a is even number" )  
  9.    }  
  10. }  

Output:

a is even number

Go if-else

The if-else is used to test the condition. If condition is true, if block is executed otherwise else block is executed.

Syntax :

  1. if(boolean_expression) {  
  2.    /* statement(s) got executed only if the expression results in true */  
  3. else {  
  4.    /* statement(s) got executed only if the expression results in false */  
  5. }  

Go if-else example

  1. package main  
  2. import "fmt"  
  3. func main() {  
  4.    /* local variable definition */  
  5.    var a int = 10;  
  6.    /* check the boolean condition */  
  7.    if ( a%2 == 0 ) {  
  8.       /* if condition is true then print the following */  
  9.       fmt.Printf("a is even\n");  
  10.    } else {  
  11.       /* if condition is false then print the following */  
  12.       fmt.Printf("a is odd\n");  
  13.    }  
  14.    fmt.Printf("value of a is : %d\n", a);  
  15. }  

Output:

a is even
value of a is : 10

Go If-else example: with input from user

  1. func main() {  
  2.    fmt.Print("Enter number: ")  
  3.    var input int  
  4.   fmt.Scanln(&input)  
  5.    fmt.Print(input)  
  6.    /* check the boolean condition */  
  7.    if( input % 2==0 ) {  
  8.       /* if condition is true then print the following */  
  9.       fmt.Printf(" is even\n" );  
  10.    } else {  
  11.       /* if condition is false then print the following */  
  12.       fmt.Printf(" is odd\n" );  
  13.    }  
  14. }  

Output:

Enter number: 10
10 is even

Go If else-if chain

The Go if else-if chain is used to execute one statement from multiple conditions.

We can have N numbers of if-else statement. It has no limit.

The curly braces{ } are mandatory in if-else statement even if you have one statement in it. The else-if and else keyword must be on the same line after the closing curly brace }.

Go If else-if chain Example

  1.       
  2. package main  
  3. import "fmt"  
  4. func main() {  
  5.    fmt.Print("Enter text: ")  
  6.    var input int  
  7.    fmt.Scanln(&input)  
  8.    if (input < 0 || input > 100) {  
  9.       fmt.Print("Please enter valid no")  
  10.    } else if (input >= 0 && input < 50  ) {  
  11.       fmt.Print(" Fail")  
  12.    } else if (input >= 50 && input < 60) {  
  13.       fmt.Print(" D Grade")  
  14.    } else if (input >= 60 && input < 70  ) {  
  15.       fmt.Print(" C Grade")  
  16.    } else if (input >= 70 && input < 80) {  
  17.       fmt.Print(" B Grade")  
  18.    } else if (input >= 80 && input < 90  ) {  
  19.       fmt.Print(" A Grade")  
  20.    } else if (input >= 90 && input <= 100) {  
  21.       fmt.Print(" A+ Grade")  
  22.    }  
  23. }  

Output:

Enter text: 84
 A Grade

Go Nested if-else

We can also nest the if-else statement to execute one statement from multiple conditions.

Syntax

  1. if( boolean_expression 1) {  
  2.     /* statement(s) got executed only if the expression 1 results in true */  
  3.    if(boolean_expression 2) {  
  4.     /* statement(s) got executed only if the expression 2 results in true */  
  5.    }  
  6. }  

nested if-else example

  1. package main  
  2. import "fmt"  
  3. func main() {  
  4.    /* local variable definition */  
  5.    var x int = 10  
  6.    var y int = 20  
  7.    /* check the boolean condition */  
  8.    if( x >=10 ) {  
  9.       /* if condition is true then check the following */  
  10.       if( y >= 10 )  {  
  11.          /* if condition is true then print the following */  
  12.          fmt.Printf("Inside nested If Statement \n" );  
  13.       }  
  14.    }  
  15.    fmt.Printf("Value of x is : %d\n", x );  
  16.    fmt.Printf("Value of y is : %d\n", y );  
  17. }  

Output:

Inside nested If Statement 
Value of x is : 10
Value of y is : 20