DEV Community

k leaf
k leaf

Posted on

assigning the result of this type assertion to a variable (switch value := value.(type))

assigning the result of this type assertion to a variable (switch value := value.(type)) could eliminate type assertions in switch cases

warning message code



package main

import "fmt"

func main() {
    values := []interface{}{1, "two", 3.0}

    for _, value := range values {
        switch value.(type) {
        case int:
            v := value.(int)
            fmt.Printf("%d is an integer\n", v)
        case string:
            v := value.(string)
            fmt.Printf("%s is a string\n", v)
        case float64:
            v := value.(float64)
            fmt.Printf("%f is a float\n", v)
        default:
            fmt.Println("Unknown type")
        }
    }
}



Enter fullscreen mode Exit fullscreen mode

Change to this

correct version of code



package main

import "fmt"

func main() {
    values := []interface{}{1, "two", 3.0}

    for _, value := range values {
        switch v := value.(type) {
        case int:
            fmt.Printf("%d is an integer\n", v)
        case string:
            fmt.Printf("%s is a string\n", v)
        case float64:
            fmt.Printf("%f is a float\n", v)
        default:
            fmt.Println("Unknown type")
        }
    }
}


Enter fullscreen mode Exit fullscreen mode

In this example, we have a slice of empty interfaces ([]interface{}) containing values of different types. We use a for loop to iterate through the values, and within the loop, we use a type assertion in the switch statement to determine the actual type of each value and perform different actions based on the type.

By using the type assertion (value.(type)), we can access the underlying type of value without the need for separate type assertions for each case. This makes the code more concise and eliminates the need for repetitive type checks.

Top comments (3)

Collapse
 
kleaf profile image
k leaf

again

Collapse
 
kleaf profile image
k leaf

comment

Collapse
 
kleaf profile image
k leaf

comment here