Golang无法反射到map[interface{}]interface{}类型。

huangapple go评论90阅读模式
英文:

golang can't reflect to map[interface{}]interface{}

问题

我的原始问题是,我想将URL.Values解析为通用类型(map[interface{}]interface{}),然后编辑/添加一些值,然后将其转换为JSON字符串并放入PostgreSQL的JSON列中。

我尝试使用以下代码进行解析,但是content似乎为空,而err为false。request.URL.Query()打印了一个很好的map对象。

v := reflect.ValueOf(request.URL.Query())
i := v.Interface()
content, err := i.(map[interface{}]interface{})

// 进行一些操作

jsonString, _ := json.Marshal(content)

// 添加到数据库

为什么它为空?我想得太泛化了吗?

英文:

My original problem is I want to parse URL.Values to a generic type (map[interface{}]interface{}) edit/add some values then convert it to JSON string and put it to PostgreSQL JSON column.

I tried this code to parse it but content seems to be null whereas err is false. request.URL.Query() prints a nice map object.

v := reflect.ValueOf(request.URL.Query())
i := v.Interface()
content, err := i.(map[interface{}]interface{})

// Do some operations

jsonString, _ := json.Marshal(content)

// Add to DB

Why is it null? Also am I thinking too generic?

答案1

得分: 3

content, err := i.(map[interface{}]interface{}),这不是一个类型转换,而是一个类型断言。你在断言接口的类型是map[interface{}]interface{},但实际上它的类型是map[string][]string。你得到的值是null,是因为断言失败了。我非常怀疑error是false。

你是不是想得太泛化了?当然是的。我想不出为什么集合类型需要改变的任何理由...你可以向其中添加任何内容,将其写入数据库。据我所知,没有任何限制。

英文:

content, err := i.(map[interface{}]interface{}), this isn't a cast, it's a type assertion. You're saying (asserting) that interface is of type map[interface{}]interface{}, it's not. It's of type map[string][]string. You get null as the value because it fails. I highly doubt error is false.

Are you thinking too generic? Of course you are. I can't think of any reason why the collections type needs to change... Append what you want to it, write it to your db. There's nothing preventing that afaik?

huangapple
  • 本文由 发表于 2015年7月10日 00:22:20
  • 转载请务必保留本文链接:https://go.coder-hub.com/31323087.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定