How to map text file content in array of structure in go?

huangapple go评论86阅读模式
英文:

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)
}

huangapple
  • 本文由 发表于 2014年7月3日 21:28:47
  • 转载请务必保留本文链接:https://go.coder-hub.com/24555004.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定