dongyong8071 2013-12-25 02:22
浏览 201

在Go中将CSV记录解组为struct

The problem how to automatically deserialize/unmarshal record from CSV file into Go struct.

For example, I have

type Test struct {
  Name string
  Surname string
  Age int
}

And CSV file contains records

John;Smith;42
Piter;Abel;50

Is there an easy way to unmarshal those records into struct except by using "encoding/csv" package for reading record and then doing something like

record, _ := reader.Read()
test := Test{record[0],record[1],atoi(record[2])}
  • 写回答

3条回答 默认 最新

  • doushan3511 2013-12-25 05:26
    关注

    You could bake your own. Perhaps something like this:

    package main
    
    import (
        "fmt"
        "strconv"
        "strings"
    )
    
    type Test struct {
        Name    string
        Surname string
        Age     int
    }
    
    func (t Test) String() string {
        return fmt.Sprintf("%s;%s;%d", t.Name, t.Surname, t.Age)
    }
    
    func (t *Test) Parse(in string) {
        tmp := strings.Split(in, ";")
        t.Name = tmp[0]
        t.Surname = tmp[1]
        t.Age, _ = strconv.Atoi(tmp[2])
    }
    
    func main() {
    
        john := Test{"John", "Smith", 42}
        fmt.Printf("john:%v
    ", john)
    
        johnString := john.String()
        fmt.Printf("johnString:%s
    ", johnString)
    
        var rebornJohn Test
        rebornJohn.Parse(johnString)
        fmt.Printf("rebornJohn:%v
    ", rebornJohn)
    
    }
    
    评论

报告相同问题?

悬赏问题

  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?