Golang Tutorial

Fundamentals

Control Statements

Functions & Methods

Structure

Arrays & Slices

String

Pointers

Interfaces

Concurrency

Switch Statement in Go

The switch statement in Go is a multi-way branch statement. It allows you to test variable values against multiple cases and execute one or more blocks of code based on the outcome. In this tutorial, we will explore the use of the switch statement in Go.

1. Basic Switch Statement

package main

import "fmt"

func main() {
    num := 3

    switch num {
    case 1:
        fmt.Println("One")
    case 2:
        fmt.Println("Two")
    case 3:
        fmt.Println("Three")
    default:
        fmt.Println("Number not recognized")
    }
    // Outputs: Three
}

2. Multiple Cases

A single case can handle multiple possible values.

day := "Fri"

switch day {
case "Mon", "Tue", "Wed", "Thu", "Fri":
    fmt.Println("It's a weekday!")
case "Sat", "Sun":
    fmt.Println("It's the weekend!")
default:
    fmt.Println("Invalid day!")
}
// Outputs: It's a weekday!

3. Expression in Switch

Instead of a simple variable, you can also have an expression in the switch.

a, b := 10, 20

switch a + b {
case 30:
    fmt.Println("The sum is 30")
case 40:
    fmt.Println("The sum is 40")
default:
    fmt.Println("The sum is something else")
}
// Outputs: The sum is 30

4. Switch with Initializer

You can initialize a variable right within the switch statement.

switch num := 5; num {
case 3:
    fmt.Println("Three")
case 4:
    fmt.Println("Four")
case 5:
    fmt.Println("Five")
}
// Outputs: Five

5. Switch Without an Expression (Type Switch)

A switch without an expression is an alternate way to express if/else logic. It's also used to discover the dynamic type of an interface variable.

var x interface{} = 7

switch x.(type) {
case int:
    fmt.Println("Integer")
case float64:
    fmt.Println("Float64")
case string:
    fmt.Println("String")
default:
    fmt.Println("Unknown type")
}
// Outputs: Integer

6. Fallthrough in Go

In many programming languages, switch cases fall through by default. In Go, they do not fall through by default. However, you can use the fallthrough keyword to achieve this behavior.

num := 3

switch num {
case 1:
    fmt.Println("One")
case 2:
    fmt.Println("Two")
case 3:
    fmt.Println("Three")
    fallthrough
case 4:
    fmt.Println("Four")
default:
    fmt.Println("Number not recognized")
}
// Outputs:
// Three
// Four

Note: The use of fallthrough can be confusing, and its usage is often discouraged unless there's a strong reason to use it.

Key Takeaways:

  • The switch statement in Go allows multi-way branching.
  • Cases in Go's switch don't fall through by default. If needed, you can use the fallthrough keyword.
  • You can use a switch without an expression as an alternative to if/else chains.
  • Go supports type switches to discover the dynamic type of an interface variable.

The switch statement is a powerful tool in Go and can be used to make your code more readable when dealing with multiple conditions or choices.

  1. Switch case fallthrough in Go:

    fallthrough statement in a switch case causes control to move to the next case, even if it doesn't match.

    package main
    
    import "fmt"
    
    func main() {
        num := 2
    
        switch num {
        case 1:
            fmt.Println("One")
            fallthrough
        case 2:
            fmt.Println("Two")
        case 3:
            fmt.Println("Three")
        }
    }
    
  2. Golang switch with multiple conditions:

    Switch statements can include multiple conditions in a single case.

    package main
    
    import "fmt"
    
    func main() {
        num := 2
    
        switch num {
        case 1, 3, 5:
            fmt.Println("Odd")
        case 2, 4, 6:
            fmt.Println("Even")
        }
    }
    
  3. Type switches in Go:

    Type switches are used when you want to compare the type of an interface value.

    package main
    
    import "fmt"
    
    func checkType(x interface{}) {
        switch x.(type) {
        case int:
            fmt.Println("Integer")
        case string:
            fmt.Println("String")
        default:
            fmt.Println("Unknown type")
        }
    }
    
    func main() {
        checkType(42)
        checkType("Hello")
    }
    
  4. Using switch with interfaces in Golang:

    Switch statements can be used with interfaces, allowing type-based branching.

    package main
    
    import "fmt"
    
    type Shape interface {
        Area() float64
    }
    
    type Circle struct {
        Radius float64
    }
    
    type Rectangle struct {
        Width, Height float64
    }
    
    func (c Circle) Area() float64 {
        return 3.14 * c.Radius * c.Radius
    }
    
    func (r Rectangle) Area() float64 {
        return r.Width * r.Height
    }
    
    func printArea(s Shape) {
        switch v := s.(type) {
        case Circle:
            fmt.Println("Circle area:", v.Area())
        case Rectangle:
            fmt.Println("Rectangle area:", v.Area())
        default:
            fmt.Println("Unknown shape")
        }
    }
    
    func main() {
        circle := Circle{Radius: 2}
        rectangle := Rectangle{Width: 3, Height: 4}
    
        printArea(circle)
        printArea(rectangle)
    }
    
  5. Golang switch statement examples:

    A basic switch statement example with different cases.

    package main
    
    import "fmt"
    
    func main() {
        fruit := "apple"
    
        switch fruit {
        case "apple":
            fmt.Println("It's an apple.")
        case "banana":
            fmt.Println("It's a banana.")
        default:
            fmt.Println("Unknown fruit.")
        }
    }
    
  6. Nested switch statements in Go:

    Switch statements can be nested within each other.

    package main
    
    import "fmt"
    
    func main() {
        num := 5
    
        switch {
        case num > 0:
            switch {
            case num%2 == 0:
                fmt.Println("Positive even number")
            default:
                fmt.Println("Positive odd number")
            }
        case num < 0:
            fmt.Println("Negative number")
        default:
            fmt.Println("Zero")
        }
    }
    
  7. Golang switch on type assertion:

    Using switch on type assertion to handle different types.

    package main
    
    import "fmt"
    
    func checkType(x interface{}) {
        switch v := x.(type) {
        case int:
            fmt.Println("Integer:", v)
        case string:
            fmt.Println("String:", v)
        default:
            fmt.Println("Unknown type")
        }
    }
    
    func main() {
        checkType(42)
        checkType("Hello")
    }
    
  8. Break and fallthrough in Go switch:

    Using break to exit a switch and fallthrough to move to the next case.

    package main
    
    import "fmt"
    
    func main() {
        num := 2
    
        switch num {
        case 1:
            fmt.Println("One")
            break
        case 2:
            fmt.Println("Two")
            fallthrough
        case 3:
            fmt.Println("Three")
        }
    }