【问题标题】:How cast type when the original arg is a pointer当原始 arg 是指针时如何转换类型
【发布时间】:2020-04-10 11:34:40
【问题描述】:

所以我有这个:

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

问题是:

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

返回一个指针。我尝试像这样取消引用指针:

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

但我明白了:

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

所以我想既然 Get 方法不返回指针,那么我不能取消引用它。

【问题讨论】:

  • 看起来muxctx.Get 返回了一个接口{}。如果您知道该接口的类型,则可以对该类型进行类型断言。

标签: go gorilla mux


【解决方案1】:

很确定你想要类似的东西:

// 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

最后,确定你有你想要的类型(如果需要,使用反射),否则程序会因错误的类型强制而恐慌。

【讨论】:

    【解决方案2】:

    Get方法是func (m *muxctx) Get(string) interface{},返回值类型是interface{},如果value是int(1)类型是interface{},如果value是map[string]interface{}类型返回类型也是interface{}。

    所以ptr, ok := muxctx.Get(req, "req-body-map")中的ptr类型是interface{},必须将interface{}ptr类型转换为需要的类型,例如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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-08-21
      • 1970-01-01
      • 1970-01-01
      • 2010-12-29
      • 2016-11-23
      • 1970-01-01
      • 1970-01-01
      • 2015-09-17
      相关资源
      最近更新 更多