Thursday, June 23, 2011

Control structures - Go switch case statement

The switch statement may be considered a more powerful version of the if statement where multiple if-else blocks are replaced with a single switch and multiple case blocks. There are differences though between the two and we shall see them in some examples.


switch any expression of type T {
case any expression of same type T: { code to be executed if the case expression is equal to the switch expression }
case any expression of same type T: { code to be executed if this case expression is equal to the switch expression }
//any number of case statements are allowed
default: { code to be executed if none of the case expressions match the switch expression }
}


Few points to note:
* the type of the evaluated value in the switch and the case should match. For example, if the switch expression evaluates to an int and the case expression evaluates to a string, then there will be a compile error.
* if there is no expression at all in the switch, then by default it is bool
* if more than one case statements match, then the first in lexical order is executed
* unlike certain other languages, each case block is independent and code does not "fall through" (each of the case code blocks are like independent if-else code blocks. There is a fallthrough statement that you can explicitly use to obtain that behavior.)
* the code block of default is executed if none of the other case blocks match
* the case expressions need not be just constants and can have expressions
* the use of curly braces for demarcating the code blocks is optional
* the default statement is optional
* any number of case statements are allowed - even zero case statements are valid, though that wouldn’t be very useful.
* multiple match expressions can be used, each separated by commas in the case statement
* the default block can be anywhere within the switch block, and not necessarily last in lexical order

If no switch expression, the type is bool

In the example below, there is no expression for the switch, therefore it is by default boolean. In the case blocks, we use the primitve values true and false. The block that evaluates to true is executed, and none of the others are executed.

Full program
package main

import "fmt"

func main() {
    switch {
    case true: fmt.Println("first is true")
    case false: fmt.Println("second is false")
    default: fmt.Println("default")
    }
}

first is true

switch and case types have to match

In the example below, we switch on an integer value. Note that each of the case statements is also an integer. I have commented out the case i>7 as there will be a compiler error since the types don’t match.

Full program
package main

import "fmt"

func main() {
    i := 5
    switch i {
    case 4: fmt.Println("number 4")
    case 5:fmt.Println("number 5")
    case 6: fmt.Println("number 6")
    //case i>7: fmt.Println("is > 7") //will be compile error as type int and bool don't match between case and switch
    default: fmt.Println("default")
    }
}

number 5

Multiple match expressions to be separated by commas

In the example below, we check whether a given value is odd or even. Since multiple values could match, and on each we want to execute the same code, we can separate each of the match expressions with commas in a single case.

Full program
package main

import "fmt"

func main() {
    j := 4
    switch j {
    case 1,3,5,7,9: fmt.Println(j, "is odd")
    case 0,2,4,6,8: fmt.Println(j, "is even")
    default: fmt.Println(j, "is not an integer between 0 and 9")
    }

}

4 is even

Example with string type, use of default, and use of variables in case


Full program
package main

import "fmt"

func main() {
    s1 := "abcd"
    s2 := "efgh"
    switch s1 { 
    case s2: fmt.Println("the two strings are equal")
    default: fmt.Println("the two strings are NOT equal")  //since nothing else matches, the default block is executed
    }
}

the two strings are NOT equal

fallthrough statement

In certain languages like C and Java, the switch-case statement behaves slightly differently from Go: when a case block is executed, all the case blocks below it are also executed, unless explicitly terminated (by say using a break statement). In Go, this is not the default behavior, but if you want to achieve the same result, then use the fallthrough statement to indicate that the case block following the current one has to be executed.

Full program
package main

import "fmt"

func main() {
    k := 6
    switch k {
    case 4: fmt.Println("was <= 4"); fallthrough;
    case 5: fmt.Println("was <= 5"); fallthrough;
    case 6: fmt.Println("was <= 6"); fallthrough;
    case 7: fmt.Println("was <= 7"); fallthrough;
    case 8: fmt.Println("was <= 8"); fallthrough;
    default: fmt.Println("default case") 
    }
}
was <= 6
was <= 7
was <= 8
default case

6 comments:

  1. Replies
    1. Sorry, hadn't noticed that before. Updated now.

      Delete
  2. Replies
    1. Sorry, hadn't noticed that before. Updated now.

      Delete
  3. Hello there! How do you feel about commercial banners of all kinds put on personal blogs?

    ReplyDelete
    Replies
    1. You should learn Tutorial silently. The best tutorial for GoLang.

      Delete

If you think others also will find these tutorials useful, kindly "+1" it above and mention the link in your own blogs, responses, and entries on the net so that others also may reach here. Thank you.