I would like to use a type switch to call a type specific parsing function
package main
import (
"fmt"
)
func main() {
var value interface{}
value = "I am a string"
switch v := value.(type) {
case string:
parseString(value)
default:
fmt.Printf("I don't know about type %T!\n", v)
}
}
func parseString(s string) {
fmt.Println(s)
}
However this does not compile because it's missing a type assertion:
cannot use value (type interface {}) as type string in argument to parseString: need type assertion
Adding a type assertion fixes the error.
package main
import (
"fmt"
)
func main() {
var value interface{}
value = "I am a string"
switch v := value.(type) {
case string:
s, ok := value.(string)
if ok {
parseString(s)
}
default:
fmt.Printf("I don't know about type %T!\n", v)
}
}
func parseString(s string) {
fmt.Println(s)
}
But this feels redundant. I am now checking twice, whether the value is a string.
Should I choose between a type switch and type assertion? Perhaps there is a less redundant way to do this? The example is contrived. There could be many types, which is why a type switch seemed like clean solution...until I started adding type asseertions.
UpdateThis question has received multiple downvotes. I think this misses the confusing nature of Go's type switch where it appears (initially) as if the value being switched on is the type, not the value.
switch v := value.(type) {
case string:
// ...
case int:
// ...
}
v