将结构体转换为字符串切片?

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

Convert struct to slice of strings?

问题

我正在尝试使用encoding/csv包来编写CSV文件。我想要按行写入的所有数据都保存在以下结构体中:

  1. type record struct {
  2. Field0 string
  3. Field1 string
  4. Field2 string
  5. Field3 string
  6. }

csv包有一个名为Write的方法,它需要一个字符串切片作为参数。

是否可以将结构体转换为字符串切片?

英文:

I'm trying to write a CSV file using the package encoding/csv. All data I want to write per line is saved in a struct like this:

  1. type record struct {
  2. Field0 string
  3. Field1 string
  4. Field2 string
  5. Field3 string
  6. }

The csv package has a method called Write that requires a slice of strings.

Is it possible to convert a struct to a slice of strings?

答案1

得分: 3

例如,

  1. package main
  2. import (
  3. "fmt"
  4. )
  5. type record struct {
  6. Field0 string
  7. Field1 string
  8. Field2 string
  9. Field3 string
  10. }
  11. func main() {
  12. r := record{"f0", "f1", "f2", "f3"}
  13. fmt.Printf("%q\n", r)
  14. s := []string{
  15. r.Field0,
  16. r.Field1,
  17. r.Field2,
  18. r.Field3,
  19. }
  20. fmt.Printf("%q\n", s)
  21. }

输出:

  1. {"f0" "f1" "f2" "f3"}
  2. ["f0" "f1" "f2" "f3"]
英文:

For example,

  1. package main
  2. import (
  3. "fmt"
  4. )
  5. type record struct {
  6. Field0 string
  7. Field1 string
  8. Field2 string
  9. Field3 string
  10. }
  11. func main() {
  12. r := record{"f0", "f1", "f2", "f3"}
  13. fmt.Printf("%q\n", r)
  14. s := []string{
  15. r.Field0,
  16. r.Field1,
  17. r.Field2,
  18. r.Field3,
  19. }
  20. fmt.Printf("%q\n", s)
  21. }

Output:

  1. {"f0" "f1" "f2" "f3"}
  2. ["f0" "f1" "f2" "f3"]

答案2

得分: 3

我发现https://github.com/fatih/structs包非常有用...

  1. package main
  2. import (
  3. "fmt"
  4. "github.com/fatih/structs"
  5. )
  6. type record struct {
  7. Field0 string
  8. Field1 string
  9. Field2 string
  10. Field3 string
  11. }
  12. func main() {
  13. r := record{"f0", "f1", "f2", "f3"}
  14. fmt.Printf("%q\n", r)
  15. vals := structs.Values(r)
  16. fmt.Printf("%q\n", vals)
  17. }
  18. 输出:
  19. {"f0" "f1" "f2" "f3"}
  20. ["f0" "f1" "f2" "f3"]
英文:

I find the https://github.com/fatih/structs package to be quite useful...

  1. package main
  2. import (
  3. "fmt"
  4. "github.com/fatih/structs"
  5. )
  6. type record struct {
  7. Field0 string
  8. Field1 string
  9. Field2 string
  10. Field3 string
  11. }
  12. func main() {
  13. r := record{"f0", "f1", "f2", "f3"}
  14. fmt.Printf("%q\n", r)
  15. vals := structs.Values(r)
  16. fmt.Printf("%q\n", vals)
  17. }
  18. Output:
  19. {"f0" "f1" "f2" "f3"}
  20. ["f0" "f1" "f2" "f3"]

huangapple
  • 本文由 发表于 2017年4月9日 08:58:39
  • 转载请务必保留本文链接:https://go.coder-hub.com/43301956.html
匿名

发表评论

匿名网友

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

确定