英文:
How to create []string from struct in Go
问题
你可以通过使用反射来创建[]string
,从而将结构体的值转换为字符串数组。以下是一个示例代码:
import (
"reflect"
"strconv"
)
func structToStringSlice(s interface{}) []string {
v := reflect.ValueOf(s)
t := v.Type()
numFields := t.NumField()
result := make([]string, numFields)
for i := 0; i < numFields; i++ {
field := v.Field(i)
switch field.Kind() {
case reflect.Float64:
result[i] = strconv.FormatFloat(field.Float(), 'f', -1, 64)
case reflect.String:
result[i] = field.String()
}
}
return result
}
func main() {
type Person struct {
Height float64
Weight float64
Name string
Born string
}
Tim := Person{174.5, 68.3, "Tim", "United States"}
result := structToStringSlice(Tim)
fmt.Println(result) // 输出: []string{"174.5", "68.3", "Tim", "United States"}
}
在上面的代码中,structToStringSlice
函数接受一个结构体实例作为参数,并使用反射来遍历结构体的字段。根据字段的类型,将其值转换为字符串并存储在结果数组中。最后,返回转换后的字符串数组。
你可以将上述代码中的 Person
结构体和 Tim
实例替换为你自己的结构体和实例,然后调用 structToStringSlice
函数来获取转换后的字符串数组。
英文:
How can I create []string
from struct's values in Go? For example, in the following struct:
type Person struct {
Height float64
Weight float64
Name string
Born string
}
Tim := Person{174.5, 68.3, "Tim", "United States"}
What I want to get is the following one:
[]string{"174.5", "68.3", "Tim", "United States"}
Since I want to save each record which is derived from the struct to a CSV file, and Write
method of the *csv.Writer
requires to take the data as []string
, I have to convert such struct to []string
.
Of course I can define a method on the struct and have it return []string
, but I'd like to know a way to avoid calling every field (i.e. person.Height, person.Weight, person.Name...) since the actual data includes much more field.
Thanks.
答案1
得分: 3
可能有一种更简单和/或更惯用的方法来实现,但我首先想到的是使用reflect
包,代码如下:
package main
import (
"fmt"
"reflect"
)
func main() {
type Person struct {
Height float64
Weight float64
Name string
Born string
}
Tim := Person{174.5, 68.3, "Tim", "United States"}
v := reflect.ValueOf(Tim)
var ss []string
for i := 0; i < v.NumField(); i++ {
ss = append(ss, fmt.Sprintf("%v", v.Field(i).Interface()))
}
fmt.Println(ss)
}
希望对你有帮助!
英文:
There may be a simpler and/or more idiomatic way to do it, but what comes to mind for me is to use the reflect
package like this:
package main
import (
"fmt"
"reflect"
)
func main() {
type Person struct {
Height float64
Weight float64
Name string
Born string
}
Tim := Person{174.5, 68.3, "Tim", "United States"}
v := reflect.ValueOf(Tim)
var ss []string
for i := 0; i < v.NumField(); i++ {
ss = append(ss, fmt.Sprintf("%v", v.Field(i).Interface()))
}
fmt.Println(ss)
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论