我正在尝试使用包encoding/csv
编写CSV文件。我想在每行写入的所有数据都保存在这样的结构中:
type record struct {
Field0 string
Field1 string
Field2 string
Field3 string
}
csv包有一个名为Write的方法,需要一段字符串。
是否可以将结构转换为字符串切片?
答案 0 :(得分:1)
例如,
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"]
答案 1 :(得分:1)
我发现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)
s := structs.Names(r)
fmt.Printf("%q\n", s)
}
Output:
{"f0" "f1" "f2" "f3"}
["f0" "f1" "f2" "f3"]