英文:
How to map text file content in array of structure in go?
问题
我有一个名为data.txt的文本文件:
0,0123,"Value 1"
1,0456,"Value 2"
在Go语言中,我定义了一个结构体:
type ChangeStatus struct {
  Nr1 string
  Nr2 string
  Category string
}
我是Go语言的新手,所以我想知道如何读取该文本文件,并将每一行放入ChangeStatus的数组中?
英文:
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
得分: 4
你可以使用csv.Reader来实现这个功能,例如:
func main() {
    status := []ChangeStatus{}
    f := strings.NewReader(text_file) //根据需要将此处替换为os.Open
    //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\n", status)
}
这段代码使用csv.Reader读取CSV文件,并将每行的数据存储在ChangeStatus结构体中。最后,通过fmt.Printf打印出status的内容。
英文:
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\n", status)
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论