douyu1656 2018-06-10 03:55
浏览 276
已采纳

我应该如何在golang中传递param?

I have the follow whole codes:

I hope that string convert map in golang, and use golang reflect.

The following code have simpled from my project.

package main

import (
    "encoding/json"
    "fmt"
    "reflect"
)

func main() {
    jsonStr := `{"name": "thinkerou", "age": 31, "balance": 3.14}`

    var a map[string]interface{}
    var value reflect.Value = reflect.ValueOf(&a)

    // call function and pass param
    f(jsonStr, value)

    // print result
    fmt.Println(value.Kind(), value.Interface())
}

func f(v string, value reflect.Value) {
    personMap := make(map[string]interface{})

    err := json.Unmarshal([]byte(v), &personMap)

    if err != nil {
        panic(err)
    }

    value = reflect.Indirect(value)
    value = reflect.MakeMap(value.Type())
    for k, v := range personMap {
        // set key/value
        value.SetMapIndex(reflect.ValueOf(k), reflect.ValueOf(v))
    }

    // print result
    fmt.Println(value.Kind(), value.Interface())
}

and run it and will get the result:

map map[age:31 balance:3.14 name:thinkerou]
ptr &map[]

I hope the follow result:

map map[age:31 balance:3.14 name:thinkerou]
map map[age:31 balance:3.14 name:thinkerou]

How should I pass reflect.Value param? thanks!

  • 写回答

1条回答 默认 最新

  • duanma8207 2018-06-10 04:03
    关注

    You should be able to get your map from the interface, using type assertion:

    a := i.(map[string]interface{})
    

    See "Convert Value type to Map in Golang?"

    I have modified your code here.
    Note that I don't try to mutate the f(value) argument, but I return it instead.

    func f(v string, value reflect.Value) reflect.Value {
      ...
      return value 
    }
    

    So the code becomes:

    value = f(jsonStr, value)
    fmt.Println(value.Kind(), value.Interface().(map[string]interface{}))
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测