Yeah, the way I needed it was to pass a pointer of the correct type and
have a value stored there. The problem is that when passing a pointer to an
interface, it seems that the function is unable to figure out where that
pointer points to (I guess there is an additional step of reflection needed
for that). Sure I can have a switch for each type, but then I need to
explicitly write it 8 times, which is basically what I did, was just hoping
to not have to and let the compiler do it instead - I thought that
unrolling the switch is what the compiler does, but I guess it doesn't.
On Wednesday, June 22, 2016 at 2:48:21 PM UTC+3, Marvin Renich wrote:
>
> * raido...@gmail.com >
> [160621 18:02]:
> > I have encountered some unexpected and inconsistent behavior with type
> > switches. Can someone shed some light as to why Go behaves this way?
> >
> > Take a look at https://play.golang.org/p/YPV5YPtWF8
> >
> > I would expect both of the switches to behave the same way, but for some
> > reason the one with multiple options in the case ends up with a pointer
> to
> > an interface and the one with just one option ends up with a pointer to
> the
> > correct type.
>
> (Aside: reusing the variable t makes it harder to discuss specific
> instances of that variable. I am pasting your code here with variable
> name changes.)
>
> package main
>
> import "fmt"
> import "reflect"
>
> func main() {
> var v uint8 = 0
> var t interface{} = v
> fmt.Println(fmt.Sprintf("%s %s", reflect.TypeOf(v),
> reflect.TypeOf(&v)))
> switch w := t.(type) {
> case uint8:
> fmt.Println(fmt.Sprintf("%s %s", reflect.TypeOf(w),
> reflect.TypeOf(&w)))
> }
> switch x := t.(type) {
> case uint8, int8:
> fmt.Println(fmt.Sprintf("%s %s", reflect.TypeOf(x),
> reflect.TypeOf(&x)))
> }
> }
>
> The compiler must know, at compile time, what type w and x are
> everywhere except in the switch expression itself. For w in the "case
> uint8" clause, the type of w is known to be uint8. For x in the "case
> uint8, int8" clause, it cannot be determined whether x will be uint8 or
> int8, so the compiler must use interface{} so that it can generate a
> single block of code that works for both possible case types.
>
> If you use different case clauses for the different types, you will get
> what you expected. (I.e. add a separate "case int8:" to the first
> switch statement.)
>
> ...Marvin
>
>
--
You received this message because you are subscribed to the Google Groups
"golang-nuts" group.
To unsubscribe from this group and stop receiving emails from it, send an email
to golang-nuts+unsubscr...@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.