dongquanlin1885 2018-03-19 15:17
浏览 499
已采纳

如何将map [string] interface {}中的不同值转换为golang中的string类型?

I have a map with different types in interface{} and I need to convert them all to string type. Type assertion is not enough.

package main

func main() {
    map1 := map[string]interface{}{"str1": "string one", "int1": 123, "float1": 0.123}

    var slc []string
    for _, j := range map1 {
        slc = append(slc, j.(string)) // panic: interface conversion: interface {} is int, not string
    }
}
  • 写回答

1条回答 默认 最新

  • dongmi5177 2018-03-19 15:31
    关注

    @Adrian and @Kaedys comments point to the correct answer. Developing it a bit more you could do something as:

    package main
    
    import "fmt"
    
    func main() {
        map1 := map[string]interface{}{"str1": "string one", "int1": 123, "float1": 0.123}
    
        var slc []string
        for _, j := range map1 {
            switch v := j.(type) {
            case string:
                slc = append(slc, v)
            case fmt.Stringer:
                slc = append(slc, v.String())
            default:
                slc = append(slc, fmt.Sprintf("%v", v))
            }
        }
    
        fmt.Println(slc)
    }
    

    This answer will work for strings, any type that implements the fmt.Stringer interface, and will default to fmt.Sprintf("%v", ...).

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 如何用stata画出文献中常见的安慰剂检验图
  • ¥15 c语言链表结构体数据插入
  • ¥40 使用MATLAB解答线性代数问题
  • ¥15 COCOS的问题COCOS的问题
  • ¥15 FPGA-SRIO初始化失败
  • ¥15 MapReduce实现倒排索引失败
  • ¥15 ZABBIX6.0L连接数据库报错,如何解决?(操作系统-centos)
  • ¥15 找一位技术过硬的游戏pj程序员
  • ¥15 matlab生成电测深三层曲线模型代码
  • ¥50 随机森林与房贷信用风险模型