-1

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.

  • 1
    It looks like `muxctx.Get` returns an interface{}. If you know the type of that interface, you can type-assert to that type. – Burak Serdar Apr 09 '20 at 22:38

2 Answers2

1

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.

BJ Black
  • 2,483
  • 9
  • 15
0

Get method is func (m *muxctx) Get(string) interface{}, return a value type is interface{}, if value is int(1) type is interface{}, if value is map[string]interface{} type return type also interface{}.

so ptr type is interface{} in ptr, ok := muxctx.Get(req, "req-body-map"), must convert interface{} ptr type a need type,example map[string]interface{}:ptr.(*map[string]interface{}), map ptr? ptr.(map[string]interface{}), map double ptr? ptr.(**map[string]interface{})

(*(muxctx.Get(req, "req-body-map")) convert code is invalid syntax, var i interface{}; *i,i type is interface{}, not use * remove pointer,must convert i to a ptr type, example:n := i.(*int); *n or m := i.(*map[string]interface{}); *m.

golang spce doc:

Type assertions

Type switches

unsafe

Conversions

eudore
  • 705
  • 5
  • 10