DEV Community

Cover image for Golang for Experienced Developers - Part III
Samarth Gupta
Samarth Gupta

Posted on • Updated on

Golang for Experienced Developers - Part III

Hi, I'm back

This is the third part of Golang tutorial series, if you haven't checked out the first & second parts, do check it out here.

Control Constructs in Go

Go provides following statements for controlling the program flow:

If statement

Syntax:
// Regular if
if condition {
    ...
}

// Initialised if
if initialisation; condition {
    ...
}

// if-else
if condition {
    ...
} else {
    ...
}

if condition1 {
    ...
} else if condition2 {
    ...
} else {
    ...
}
Enter fullscreen mode Exit fullscreen mode
Points to remember:
  • Go provides two syntaxes for if statements, one with initialisation & one without initialisation.
  • Braces are mandatory, even for one line.
  • The { (opening brace) after the if and else must be on the same line.
  • The else if and else must be on same line as } (closing brace).
  • Can use parentheses for composite expressions with &&, ||, !
  • The ; after initialisation is required.
  • Use local assignments (:=) for initialisation in initialised if statements.
  • Scope of initialisation variable is known only within if statement.
  • Can also invoke functions to initialise variable in the initialised if statements.
Example:
package main
import ("fmt"; "runtime")

func main() {
    if platform := runtime.GOOS; platform == "linux" { // fetch os info 
      fmt.Println("linux platform")
    } else if platform  == "darwin" {
      fmt.Println("darwin platform")
    } else {
      fmt.Println("windows platform")
    }
}
Enter fullscreen mode Exit fullscreen mode

Switch Statement

Syntax:
// Regular switch
switch variable {
    case val1:
        ...
    case val2:
        ...
    default:
        ...
}

// Initialised switch 
switch initialisation; variable {
    case val1:
        ...
    case val2:
        ...
    default:
        ...
}

// Tag-less switch
switch {
    case boolexpr1:
        ...
    case boolexp2:
        ...
    default:
        ...
}
Enter fullscreen mode Exit fullscreen mode
Points to remember:
  • Go provides three syntaxes for switch statement.
  • The { (opening brace) must be on the same line as the switch
  • variable can be any type.
  • val1, val2 must be of the same type.
  • More than one value may appear in a case.
  • Breaks from each case are implicit.
  • Use keyword fallthrough to combine case conditions.
  • Braces ({ and }) are allowed in case for multiple statements.
  • Use keyword default to handle conditions that match no case
  • Keyword default may be placed anywhere in switch.
  • In tag-less switch statements, case statements must evaluate to boolean expressions.
Example:
package main
import ("fmt"; "runtime", "os")

func main() {
    switch platform := runtime.GOOS; platform {
        case "linux", "darwin", "windows":   // multiple cases
            fmt.Println("Known OS")
        default:
            fmt.Println("Unknown OS")
     }

    arg := os.Args[1]  // fetch command line argument
    num, _ := strconv.ParseFloat(arg, 64) // string to float64
    var val float64
    switch {
         case num < 0:
             num = -num
             fallthrough   // fallthrough to second case
         case num > 0:
             val = math.Sqrt(num)
         case num == 0:
             val = 0;
    }
    fmt.Println(val)    
}
Enter fullscreen mode Exit fullscreen mode

For statement

Syntax:
// Counter controlled loop
for initialisation; condition; update {
    ...
}

// Condition controlled loop
for condition {
    ...
}

// Range controlled loop
for index, value := range collection {
    ... 
}
for index := range collection {
    ...
}
Enter fullscreen mode Exit fullscreen mode
Points to remember:
  • Go provides three syntaxes for for statement.
  • No while or do while statements.
  • Braces are mandatory, even for one line.
  • Opening brace { must be on the same line as for
  • Surrounding parenthesis after for are not allowed.
  • May assign more than one counter in initialise with commas
  • Omitting condition in a condition controlled loop results in an infinite loop.
  • In range controlled loops, collection is a sequence of items (string, array, map).
  • index is the integer index at each iteration in the loop.
  • value is the item in the collection at each iteration in the loop.
Example:
package "main"
import "fmt"
import "os"

func main() {
    nargs := len(os.Args)
    // counter controlled
    for i := 1; i < nargs; i++ {
        fmt.Printf("%s ", os.Args[i])
    }

    args1 := os.Args[1:]
    // condition controlled
    for len(args) > 0 {
        fmt.Printf("%s ", args1[0])
        args1 = args1[1:]  // shift left
    }

    args2 := os.Args[1:]
    // range controlled
    for i, arg := range args {
        fmt.Printf("%d %s\n", i, arg)
    }
}
Enter fullscreen mode Exit fullscreen mode

Break & Continue Statement

Break:
  • Used inside a for, switch, or select statement.
  • Breaks out of innermost loop in multiple for statements.
  • Can be used with labels.
Continue:
  • Can only be used in for statement.
  • Continues with the next iteration of innermost loop.
  • Skips remaining body of loop.
  • Can be used with labels.
Example:
package main
import "fmt"
func main() {
    for i := 1; i < 25; i++ {
        if i % 2 != 0 { continue }
        if i > 20 { break }
        fmt.Printf("%d ", i)
    }
}
Enter fullscreen mode Exit fullscreen mode

This concludes the third part of the series. In next tutorial we'll cover functions and more, till then, Aloha.

Reach out to me here

Top comments (0)