Search code examples
gogorillamux

How cast type when the original arg is a pointer


So I have this:

v, ok := muxctx.Get(req, "req-body-map").(map[string]interface{})

the problem is that:

muxctx.Get(req, "req-body-map")

returns a pointer. I tried dereferencing the pointer like so:

(*(muxctx.Get(req, "req-body-map"))

but I get this:

Invalid indirect of '(muxctx.Get(req, "req-body-map"))' (type 'interface{}') 

so I suppose since the Get method doesn't return a pointer, then I can't dereference it.


Solution

  • Pretty sure you want something like:

    // You really want this to be two variables, lest you go mad.
    // OK here is mostly to see whether the value exists or not, which is what
    // presumably you're testing for.  Get that out of the way before trying to
    // get fancy with type coercion.
    //
    ptr, ok := muxctx.Get(req, "req-body-map")
    
    ... // Do other stuff (like your if test maybe)...
    
    // Now coerce and deref.  We coerce the type inside parens THEN we try to
    // dereference afterwards.
    //
    v := *(ptr.(*map[string]interface{}))
    

    A brief example of this general technique:

    package main
    
    import "fmt"
    
    func main() {
        foo := 10
        var bar interface{}
        bar = &foo
        fmt.Println(bar)
        foobar := *(bar.(*int))
        fmt.Println(foobar)
    }
    
    $ ./spike
    0xc00009e010
    10
    

    Finally, be really sure you have the type you want (using reflection if needbe) or risk the program panic'ing on a bad type coercion.