Skip to main content

Controlling Program Flow of golang

 


Overview

In this blog I am going to talk about the topic below.

Loop

You can use loop as below. here i variable is declared inside the loop so the value will be valid in side the loop.

 Example 

      
    package main

    import (
        "fmt"
    )

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

    }
    
  

output :

    0
    1
    2
    3
    4
    5
  

Break in Loop

what Break statement dose is it will break out from the loop. 
      package main

      import (
          "fmt"
      )

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

      }
  

output :

    0
    1
    2
in the example you can see when loop comes to the point when i == 2 then it break out from the loop and end the program. this why it out put the value of i until it is 2.

Continue in Loop

what Continue statement dose is it will break out from the loop but will continue with the next iteration that loop. but it will ignore every code after that statement. 
  package main
  import ("fmt")

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

output :

  0
  hello
  1
  hello
  2
  3
  hello
  4
  hello
  
if you can see, in the example program is not printing the hello string when i == 2. but continues with the loops next iteration. 

Infinity Loop

you can initiate infinite loop as below.
    package main

    import (
        "fmt"
    )

    func main() {
    	i := 1
        for {
            fmt.Println(i)
        }

    }

Collection Loop

you can iterate any collection using normal loop. but go has a very minimalistic way of looping a collection where you can iterate collection in a simple way which is range.
  package main
  import ("fmt")

  func main() {
      array := []string{"hello","world","!!!"}
      marks := map[string]int{"Bangla":80,"English":90,"Science":95}

      for i,v := range array {
          fmt.Println(i,v)
      }

      for i,v := range marks {
          fmt.Println(i,v)
      }
  }  

output :

  0 hello
  1 world
  2 !!!
  Bangla 80
  English 90
  Science 95
  
if you can see in the example. range loop is assigning index and value in variable i and v and printing it.

Switch

Switch on golang is parity much self explanatory. you can understand switch by the example below.
  package main
  package main

  import (
      "fmt"
  )

  func main() {
      nameAgeList := map[string]int{"Alax":18,"Jack":10,"Dani":21}

      for name,age := range nameAgeList {
          switch name {
          case "Alax" :
              fmt.Println("go to collage your age is",age)

          case "Jack" :
              fmt.Println("go to school your age is",age)

          case "Dani" :
              fmt.Println("go to University your age is",age)	
          }

      } 

  }

output :

  go to collage your age is 18
  go to school your age is 10
  go to University your age is 21

Panic

Panic is used in golang where program hits a position that it doesn't knows what to do. i know you can use error and exceptions in go for that but in panic it will terminate the program and report where it hits the problem.
  package main

  import (
      "fmt"
  )

  func main() {
      nameAgeList := map[string]int{"Alax":18,"Jack":19,"Dani":21}

      for name,age := range nameAgeList {
          switch name {
          case "Alax" :
              fmt.Println("go to collage your age is",age)

          case "Jack" :
              if age > 18 {
                  panic("somthing is worng")
              }
              fmt.Println("go to school your age is",age)

          case "Dani" :
              fmt.Println("go to University your age is",age)	
          }

      } 

  }

output :

    go to collage your age is 18
    panic: somthing is worng

    goroutine 1 [running]:
    main.main()
        /tmp/sandbox467193843/prog.go:17 +0x3d1
  












Comments

Popular posts from this blog

CRUD with Golang

  Overview this blog will be about a  basic crud app with golang .   this app will provide API to store, update, delete information . you need to know the basics of golang to understand this project. if you do not have the basics knowledge  about golang I would suggest you to read my previous blog.  I have uploaded my code in  GitHub. click the link to clone or download this project  I am going to talk about the topic below. Project setup Data handling controller Project setup  Initiate mod and set up project as per golang. if you don't know how to setup golang project i would suggest you to have a look at my blog  Creating a project with golang . this is a really short blog. you will have a quick over view of how to setup a project with golang.  so now that you have setup the project then the folder structure will be as below. Data Handling data store, delete and update will be handled in the user module. code is given below  package moduls import ( "errors&quo

Primitive data type of Golang

Overview In this blog I am going to talk about the date types and variables in go. and the topics bellow  Declaring and initializing variables   explicit initialization of variables   implicit initialization of variables complex data type list of data type Pointer pointer operator dereferencing operator address of operator Constant Iota and constant expression Declaring and initializing variables there are 2 ways you can declarer and initialize a variable they are explicit initialization variables  implicit initialization variables  Explicit initialization of variables  in this way you have to tell the compiler every thing you need to declare a variable. var i int i = 20 var j int = 3 fmt.Println(i,j) var f float32 = 32.233 fmt.Println(f)  in this way we are explicitly telling what will be the input type for that variable. Implicit initialization of variables  in this way of declaring a variable. we don't have to tell the compiler what type of data it will take on that

Creating a project with Golang

Overview    You can run a go file with out making a project. But the standard way to use go is to create a project or you can call it a space where you will be putting your go code, on the other hand it is a work space, but in Go Lang we call it module. In Go Lang modules are the official way of organize go code. in this blog I am going to explain the way you create a model and first hello world with that project. Explanation To Module you need to run the command bellow go mod init <module name>  If you can see I have named my module github.com/TahimFaisal/golang. the name of the module is called module initializer. this is the standard way of initialization. And for the go get command it will it will know where to go and get the mod if it cannot find the mod locally.  Okay, soon after you ran the command you will get a file named go.mod in your working directory  it will be having module initializer and the version of go your using.     now create a main.go file and write