在Golang中将[]interface转换为[]string。

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

Convert []interface to []string in Golang

问题

我正在使用github.com/fatih/structs包将结构体的所有字段值转换为[]interface{},使用toValues()函数。请参见这里。这个方法很好用,但是最终我想要使用csv包将这些值写入csv文件。csv.Write()函数需要[]string作为输入。

简而言之:我该如何将toValues()的输出轻松地转换为字符串数组?

英文:

I'm using the github.com/fatih/structs package to convert values of all fields of a struct into []interface{} with the toValues() function. See here. This works fine, but eventually I want to write the values to a csv file by using the csv package. The csv.Write() function requires []string as input.

So in short: how can I easily convert the output of toValues() into an array of strings?

答案1

得分: 48

你不能简单地将[]interface{}转换为[]string,即使所有的值都是具体类型string,因为这两种类型具有不同的内存布局/表示方式。有关详细信息,请参阅https://stackoverflow.com/questions/12990338/cannot-convert-string-to-interface。

你必须定义不同类型的值如何由string值表示。

最简单和合理的方法是遍历这些值,并使用fmt.Sprint()获取每个值的string表示,例如:

t := []interface{}{
	"zero",
	1, 2.0, 3.14,
	[]int{4, 5},
	struct{ X, Y int }{6, 7},
}
fmt.Println(t)

s := make([]string, len(t))
for i, v := range t {
	s[i] = fmt.Sprint(v)
}
fmt.Println(s)
fmt.Printf("%q\n", s)

输出结果(在Go Playground上尝试):

[zero 1 2 3.14 [4 5] {6 7}]
[zero 1 2 3.14 [4 5] {6 7}]
["zero" "1" "2" "3.14" "[4 5]" "{6 7}"]
英文:

You can't simply convert []interface{} to []string even if all the values are of concrete type string, because those 2 types have different memory layout / representation. For details see https://stackoverflow.com/questions/12990338/cannot-convert-string-to-interface.

You have to define how you want values of different types to be represented by string values.

The easiest and sensible way would be to iterate over the values, and use fmt.Sprint() to obtain a string representation of each, e.g.:

t := []interface{}{
	"zero",
	1, 2.0, 3.14,
	[]int{4, 5},
	struct{ X, Y int }{6, 7},
}
fmt.Println(t)

s := make([]string, len(t))
for i, v := range t {
	s[i] = fmt.Sprint(v)
}
fmt.Println(s)
fmt.Printf("%q\n", s)

Output (try it on the Go Playground):

[zero 1 2 3.14 [4 5] {6 7}]
[zero 1 2 3.14 [4 5] {6 7}]
["zero" "1" "2" "3.14" "[4 5]" "{6 7}"]

答案2

得分: 0

你可以这样做:

    func text(msg ...interface{}) string {
        return fmt.Sprintf("%+v", msg...)
    }
英文:

you can, just do:

    func text(msg ...interface{}) string {
        return fmt.Sprintf("%+v", msg...)
    }

答案3

得分: -1

使用fmt.Sprintf将接口值转换为字符串。实际上,这种技术可以用于获取任何数据结构的字符串表示。

以下是代码示例:

var Foo interface{} = "Value"

str := fmt.Sprintf("%v", Foo)

请注意,%v是格式化字符串中的占位符,它表示将值以默认格式输出。在这个例子中,Foo的值将被转换为字符串并赋给变量str

英文:

Use fmt.Sprintf to convert an interface value to a string. In fact, this technique can be used to get a string representation of any data structure.

Here is the code sample,

var Foo interface{} = "Value"

str := fmt.Sprintf("%v", Foo)

huangapple
  • 本文由 发表于 2017年5月17日 22:33:27
  • 转载请务必保留本文链接:https://go.coder-hub.com/44027826.html
匿名

发表评论

匿名网友

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

确定