英文:
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"]
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论