9. Go - IF/THEN and Switches

IF/ELSE IF/ELSE:

package main

func main() {
    x := 4

    if x == 5 {

    } else if x == 6 {

    } else {

    }

}


Switches:

// putting value expression in front of switch for cases to check. if empty, run bool as true by default

package main

import "fmt"

func main() {

    switch {

    case 5 == 5:
        fmt.Println("one")
    case true:
        fmt.Println("two")

    }

}

// can include multiple variablevalue checks by separation of a comma

    case 5 == 5, 2 == 5:
        fmt.Println("one")

// include fallthrough to enable the check and not break the switch. fallthrough also makes case after it run even if false. (one fallthrough valid for one case. multiple fallthroughs needed to fall through entire switch statement)

package main

import "fmt"

func main() {

    switch {

    case 5 == 5, 2 == 5:
        fmt.Println("one")
        fallthrough
    case false:
        fmt.Println("false")
    case true:
        fmt.Println("two")

    }

}

// default case, when nothing is true

    switch false {

    case 5 == 5:
        fmt.Println("one")
    case true:
        fmt.Println("two")
    default:
        fmt.Println("HELLO")
    }


Can get the type of the variable if it is a interface object by using dot notation:

// speciess is a interface

// doge and humana are type objects belonging in the interface

func giveInfo(s speciess) {
    switch s.(type) {
    case doge:
        fmt.Println("DOG")
    case humana:
        fmt.Println("HUMAN")
    default:
        fmt.Println("NONE")
    }
}


Comments

Popular posts from this blog

2. FreeCodeCamp - Dynamic Programming - Learn to Solve Algorithmic Problems & Coding Challenges

20. Data Analytics - Analyze Data to Answer Questions - Week 1

3. Algorithms - Selection Sort