当原始参数是指针时如何转换类型

How cast type when the original arg is a pointer

所以我有这个:

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

问题是:

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

return是一个指针。我试过像这样取消引用指针:

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

但我明白了:

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

所以我想因为 Get 方法没有 return 指针,所以我不能取消引用它。

很确定你想要这样的东西:

// 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{}))

此通用技术的一个简短示例:

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

最后,确定你有你想要的类型(如果需要使用反射)或者冒着程序因错误的类型转换而恐慌的风险。

Get方法是func (m *muxctx) Get(string) interface{},return一个值类型是interface{},如果value是int(1)类型是interface{},如果value是map[string]interface {} 输入 return 也输入接口{}。

so ptr type is interface{} in ptr, ok := muxctx.Get(req, "req-body-map"), 必须把interface{} ptr type转换成需要的类型,example map[string]interface{}:ptr.(*map[string]interface{}), map ptr? ptr.(map[string]interface{}),地图双指针? ptr.(**map[string]interface{})

(*(muxctx.Get(req, "req-body-map"))转换代码语法无效,var i interface{}; *i,i类型为interface{},不能使用*移除指针,必须将i转换为ptr类型,例如:n := i.(*int); *nm := i.(*map[string]interface{}); *m.

golang spce 文档:

Type assertions

Type switches

unsafe

Conversions