doushi3819244 2014-07-03 13:28
浏览 12
已采纳

如何在结构数组中映射文本文件内容?

I have a text file data.txt:

0,0123,"Value 1"
1,0456,"Value 2"

In Go I have defined struct:

type ChangeStatus struct {
  Nr1 string
  Nr2 string
  Category string
}

I am new to Go so I was wondering how can I read that text file and put each text file line into array of ChangeStatus?

  • 写回答

1条回答 默认 最新

  • drox90250557 2014-07-03 13:56
    关注

    You could use csv.Reader for that, for example:

    func main() {
        status := []ChangeStatus{}
        f := strings.NewReader(text_file) //replace this with os.Open as needed
        //defer f.Close()
        r := csv.NewReader(f)
        for {
            if parts, err := r.Read(); err == nil {
                cs := ChangeStatus{parts[0], parts[1], parts[2]}
                status = append(status, cs)
            } else {
                break
            }
        }
        fmt.Printf("%+v
    ", status)
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 yolov5自定义Prune报错,如何解决?
  • ¥15 电磁场的matlab仿真
  • ¥15 mars2d在vue3中的引入问题
  • ¥50 h5唤醒支付宝并跳转至向小荷包转账界面
  • ¥15 算法题:数的划分,用记忆化DFS做WA求调
  • ¥15 chatglm-6b应用到django项目中,模型加载失败
  • ¥15 CreateBitmapFromWicBitmap内存释放问题。
  • ¥30 win c++ socket
  • ¥15 C# datagridview 栏位进度
  • ¥15 vue3页面el-table页面数据过多