doufeng1249
2017-04-09 00:58
浏览 80
已采纳

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

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?

图片转代码服务由CSDN问答提供 功能建议

我正在尝试使用 encoding / csv 包编写CSV文件。 我想每行写入的所有数据都保存在这样的结构中:

  type record struct {
 Field0字符串
 Field1字符串
 Field2字符串
 Field3字符串 
} 
   
 
 

csv程序包具有一种称为需要一个字符串切片的

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

  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

2条回答 默认 最新

  • douweng5420 2017-04-09 01:23
    已采纳

    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
    ", r)
        s := []string{
            r.Field0,
            r.Field1,
            r.Field2,
            r.Field3,
        }
        fmt.Printf("%q
    ", s)
    }
    

    Output:

    {"f0" "f1" "f2" "f3"}
    ["f0" "f1" "f2" "f3"]
    
    打赏 评论
  • duanpuluan0480 2019-09-10 16:04

    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
    ", r)
        s := structs.Names(r)
        fmt.Printf("%q
    ", s)
    }
    Output:
    
    {"f0" "f1" "f2" "f3"}
    ["f0" "f1" "f2" "f3"]
    
    打赏 评论

相关推荐 更多相似问题