Go 是否将贴图值转换为无括号的纯字符串?
我有一个像这样的映射字符串Go 是否将贴图值转换为无括号的纯字符串?,go,Go,我有一个像这样的映射字符串 map[first:[hello] second:[world]] 问题是,当我迭代它并返回值时,它们返回[hello][world],我希望它们只返回hello world // currentMap is of type map[interface{}]interface{} originally newStringMap := make(map[string]interface{}) for k, v := range currentMap { ne
map[first:[hello] second:[world]]
问题是,当我迭代它并返回值时,它们返回[hello][world]
,我希望它们只返回hello world
// currentMap is of type map[interface{}]interface{} originally
newStringMap := make(map[string]interface{})
for k, v := range currentMap {
newStringMap[k.(string)] = v
}
return newStringMap
如何做到这一点?从您提供的以下信息: 当我迭代它并返回值时,它们返回[hello][world] 似乎您的
currentMap
实际上将字符串片段[]string
存储为值,位于接口{}
类型后面。假设上面这一行表示您在使用fmt.Println()或类似函数打印地图时看到了这一点
map[first:[hello]second:[world]]
以下是您的问题的可能再现和解决方案:
package main
import (
"fmt"
)
func main() {
currentMap := make(map[interface{}]interface{})
currentMap["first"] = []string{"hello"}
currentMap["second"] = []string{"world"}
newStringMap := make(map[string]interface{})
fmt.Println("Problem:")
fmt.Printf("%v\n", currentMap)
fmt.Println("\nSolution:")
for k, v := range currentMap {
lst, ok := v.([]string)
//fmt.Println(lst, ok)
if ok && len(lst) > 0 {
newStringMap[k.(string)] = v.([]string)[0]
} else {
newStringMap[k.(string)] = nil
}
}
fmt.Printf("%v\n", newStringMap)
}
哪些输出到:
Problem:
map[first:[hello] second:[world]]
Solution:
map[first:hello second:world]
在这里试试
存储在currentMap
中的内容不一定总是类似的类型。(如果是,那么为什么会使用接口{})。也就是说,别忘了检查错误。我也试着报道同样的情况。根据地图中可能的实际类型
,您可能需要添加更多,类似于本节:
if ok && len(lst) > 0 {
newStringMap[k.(string)] = v.([]string)[0]
} else {
newStringMap[k.(string)] = nil
}
这取决于您如何获得不想要的输出,这里没有显示。请包括实际生成您得到的输出的代码。什么是“映射字符串”?这正是我的意思,干杯。