How to create []string from struct in Go

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

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, &quot;Tim&quot;, &quot;United States&quot;}

What I want to get is the following one:

[]string{&quot;174.5&quot;, &quot;68.3&quot;, &quot;Tim&quot;, &quot;United States&quot;}

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 (
    &quot;fmt&quot;
    &quot;reflect&quot;
)

func main() {
    type Person struct {
        Height float64
        Weight float64
        Name   string
        Born   string
    }

    Tim := Person{174.5, 68.3, &quot;Tim&quot;, &quot;United States&quot;}

    v := reflect.ValueOf(Tim)

    var ss []string
    for i := 0; i &lt; v.NumField(); i++ {
        ss = append(ss, fmt.Sprintf(&quot;%v&quot;, v.Field(i).Interface()))
    }

    fmt.Println(ss)
}

huangapple
  • 本文由 发表于 2013年9月7日 16:31:32
  • 转载请务必保留本文链接:https://go.coder-hub.com/18671426.html
匿名

发表评论

匿名网友

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

确定