assigning the result of this type assertion to a variable (switch value := value.(type)) could eliminate type assertions in switch cases
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")
}
}
}
Change to this
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")
}
}
}
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)
again
comment
comment here