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

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

Convert struct to slice of strings?

问题

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

type record struct {
    Field0 string
    Field1 string
    Field2 string
    Field3 string
}

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:

type record struct {
    Field0 string
    Field1 string
    Field2 string
    Field3 string
}

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

例如,

package main

import (
    "fmt"
)

type record struct {
    Field0 string
    Field1 string
    Field2 string
    Field3 string
}

func main() {
    r := record{"f0", "f1", "f2", "f3"}
    fmt.Printf("%q\n", r)
    s := []string{
        r.Field0,
        r.Field1,
        r.Field2,
        r.Field3,
    }
    fmt.Printf("%q\n", s)
}

输出:

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

For example,

package main

import (
	"fmt"
)

type record struct {
	Field0 string
	Field1 string
	Field2 string
	Field3 string
}

func main() {
	r := record{"f0", "f1", "f2", "f3"}
	fmt.Printf("%q\n", r)
	s := []string{
		r.Field0,
		r.Field1,
		r.Field2,
		r.Field3,
	}
	fmt.Printf("%q\n", s)
}

Output:

{"f0" "f1" "f2" "f3"}
["f0" "f1" "f2" "f3"]

答案2

得分: 3

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

package main

import (
    "fmt"
    "github.com/fatih/structs"
)

type record struct {
    Field0 string
    Field1 string
    Field2 string
    Field3 string
}

func main() {
    r := record{"f0", "f1", "f2", "f3"}
    fmt.Printf("%q\n", r)
    vals := structs.Values(r)
    fmt.Printf("%q\n", vals)
}
输出:

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

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

package main

import (
    "fmt"
    "github.com/fatih/structs"
)

type record struct {
    Field0 string
    Field1 string
    Field2 string
    Field3 string
}

func main() {
    r := record{"f0", "f1", "f2", "f3"}
    fmt.Printf("%q\n", r)
    vals := structs.Values(r)
    fmt.Printf("%q\n", vals)
}
Output:

{"f0" "f1" "f2" "f3"}
["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:

确定