dongyushen9063 2018-09-12 18:44
浏览 3
已采纳

将映射值转换为无括号的纯字符串? [关闭]

I have a map string that looks like this

map[first:[hello] second:[world]]

The problem is that when I iterate over it and return the values they return [hello] [world] and I want them to just return 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

How can this be done?

  • 写回答

1条回答 默认 最新

  • douguomou5094 2018-09-12 20:25
    关注

    From the below information provided by you:

    when I iterate over it and return the values they return [hello] [world]

    It seems that your currentMap actually stores string slices []string as values, behind the interface{} type. Assuming that above line means that you see this when printing the map using fmt.Println(), or similar functions.

    map[first:[hello] second:[world]]

    Here's a possible reproduction & solution of your problem::

    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
    ", currentMap)
    
        fmt.Println("
    Solution:")
    
        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
    ", newStringMap)
    }
    

    Which outputs to:

    Problem:
    map[first:[hello] second:[world]]
    
    Solution:
    map[first:hello second:world]
    

    Try it here https://play.golang.org/p/5XAA3m6MDX_b

    It's not necessary that the content stored in currentMap is always of similar type. (if it is, then why would interface{} ever be used). Which means, don't forget your error-checking. I have tried to cover the same. You may need to add some more, based on the possible actual types in the map, similar to this section:

    if ok && len(lst) > 0 {
        newStringMap[k.(string)] = v.([]string)[0]
    } else {
        newStringMap[k.(string)] = nil
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?