Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Type switch requires (redundant) type assertion

Tags:

go

I would like to use a type switch to call a type specific parsing function

https://play.golang.org/p/2xj_owLL4ZK

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.

https://play.golang.org/p/p0nYNEEJb0Z

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.


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:
    // ...
}

I'm new to Go and incorrectly assumed v was the type. If I ran into this problem when writing Go for this first time, others may too?

like image 996
Jack Avatar asked Jun 15 '26 19:06

Jack


1 Answers

Use the value you declared in the switch:

   switch v := value.(type) {
    case string:
        // v is string here
        parseString(v)
    ...
like image 162
Burak Serdar Avatar answered Jun 17 '26 23:06

Burak Serdar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!