go - 如何将不同的值从 map[string]interface{} 转换为类型字符串

标签 go types type-assertion

我在 interface{} 中有一个具有不同类型的映射,我需要将它们全部转换为字符串类型。类型断言是不够的。

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

最佳答案

@Adrian 和@Kaedys 的评论指出了正确答案。进一步开发它,你可以做一些事情:

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

这个答案适用于字符串,任何实现 fmt.Stringer interface 的类型, 并将默认为 fmt.Sprintf("%v", ...)

关于go - 如何将不同的值从 map[string]interface{} 转换为类型字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49366380/

相关文章:

go - 在包之间使用相同结构的类型断言

go - 最小正float64值

time - 在 golang TCP 中禁用截止日期

dictionary - 如何安全地允许当前访问go中的嵌套 map ?

c++ - 将类型分配给原始文字的简写方式

mysql - PHP : MySql Data Type for monetary values

slice 指针的 Golang 类型断言

dictionary - 迭代并从 map 中获取值

javascript - 为什么javascript中的函数不接受 undefined variable ?

go - 如何在 Golang 中转换其中包含另一个结构的结构?