gpt4 book ai didi

go - 我应该如何在golang中传递参数?

转载 作者:IT王子 更新时间:2023-10-29 01:04:16 24 4
gpt4 key购买 nike

我有以下全部代码:

希望在golang中将string转换成map,并使用golang reflect。

以下代码已从我的项目中简化。

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())
}

然后运行它会得到结果:

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

希望结果如下:

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

我应该如何传递 reflect.Value 参数?谢谢!

最佳答案

您应该能够使用type assertion 从界面获取您的 map 。 :

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

参见“Convert Value type to Map in Golang?

我修改了你的code here .
请注意,我没有尝试改变 f(value) 参数,而是返回它。

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

所以代码变成:

value = f(jsonStr, value)
fmt.Println(value.Kind(), value.Interface().(map[string]interface{}))

关于go - 我应该如何在golang中传递参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50780413/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com