Skip to content

Commit ca78d48

Browse files
Refactored to make the sample more idiomatic
1 parent 8cab993 commit ca78d48

1 file changed

Lines changed: 12 additions & 15 deletions

File tree

‎chapter4/sample/main.go‎

Lines changed: 12 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -30,25 +30,22 @@ func main() {
3030
defer file.Close()
3131

3232
// Contains all the field/value mappings for every line.
33-
var allFieldValues []map[string]string
33+
var fvMappings []map[string]string
3434

3535
// Create a reader for the file.
36-
reader := bufio.NewReader(file)
36+
r := bufio.NewReader(file)
3737
for {
3838
// Read all the bytes up to the end of line marker.
39-
line, err := reader.ReadBytes('\n')
40-
if err != nil {
41-
if err != io.EOF {
42-
fmt.Println(err)
43-
return
44-
}
45-
46-
// We are done processing the file.
39+
line, err := r.ReadSlice('\n')
40+
if err == io.EOF {
4741
break
42+
} else if err != nil {
43+
fmt.Println(err)
44+
return
4845
}
4946

5047
// Capture the field/value mappings for this line.
51-
fieldValues := make(map[string]string)
48+
fv := make(map[string]string)
5249

5350
var start int
5451
var field int
@@ -67,17 +64,17 @@ func main() {
6764

6865
// Slice the value from the line and add the value to the map
6966
// for the specified field name.
70-
fieldValues[fieldNames[field]] = string(line[start:index])
67+
fv[fieldNames[field]] = string(line[start:index])
7168
field++
7269
start = index + 1
7370
}
7471

7572
// Append the field/value map to the master collection.
76-
allFieldValues = append(allFieldValues, fieldValues)
73+
fvMappings = append(fvMappings, fv)
7774
}
7875

7976
// Display all of the field/value maps.
80-
for _, fieldValues := range allFieldValues {
81-
fmt.Printf("%#v\n\n", fieldValues)
77+
for _, fv := range fvMappings {
78+
fmt.Printf("%#v\n\n", fv)
8279
}
8380
}

0 commit comments

Comments
 (0)