在Golang中将[]接口转换为[]字符串 [英] Convert []interface to []string in Golang

查看:77
本文介绍了在Golang中将[]接口转换为[]字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 github.com/fatih/structs 包来转换的所有字段的值使用toValues()函数将结构转换为[]interface{}.请参见此处.这工作正常,但最终我想通过使用csv包将值写入csv文件. csv.Write()函数需要[]string作为输入.

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.

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

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

推荐答案

即使所有值都是具体类型string,也不能简单地将[]interface{}转换为[]string,因为这两种类型具有不同的内存布局/表示形式.有关详细信息,请参见无法将[] string转换为[] interface {} .

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 Cannot convert []string to []interface {}.

您必须定义如何用string值表示不同类型的值.

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

最简单,最明智的方法是遍历值,然后使用 fmt.Sprint() 以获得每个的string表示形式,例如:

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)

输出(在游乐场上尝试):

[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}"]

这篇关于在Golang中将[]接口转换为[]字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆