我正在尝试从文件中读取并将其加载到结构切片中。我读入的行已正确加载,如块注释中所示。
我遇到的问题是class变量不断返回空值。我究竟做错了什么?
func loadClasses(path string) []Class {
var a []Class
inFile, _ := os.Open(path)
defer inFile.Close()
scanner := bufio.NewScanner(inFile)
scanner.Split(bufio.ScanLines)
var class Class
for scanner.Scan() {
var err = json.Unmarshal(scanner.Bytes(), &class)
if err != nil {
fmt.Print("Error:", err)
} else {
a = append(a, class)
}
}
return a
}
type Class struct {
id string
name string
}
/*
Sample contents
"{"id":124997,"name":"Environmental Sciences"}
{"id":123905,"name":"Physical Education"}
{"id":127834,"name":"Mandarin"}
{"id":123507,"name":"Biology"}
{"id":123883,"name":"German"}
{"id":129148,"name":"German"}
{"id":123545,"name":"Spanish"}"
*/
我的问题是两部分,结构成员必须大写,我错过了json: "id"和json: "name"
慕码人8056858
相关分类