下面的Gorang代码根据以下形式的输入为每个食谱收集了一组营养:
# applepie
- flour
- apple
- egg
# pizza
- flour
- cheese
- egg
- tomato
它在 (2) 中抱怨。assignment to entry in nil map
但是为什么?然而,每个“子映射”都初始化为 at (1) ?make
package main
import (
"bufio"
"fmt"
"os"
"regexp"
)
func main() {
nutriments := map[string][]string{
"flour":{"sugars"},
"egg":{"protein", "fat"},
"tomato":{"water", "viamins"},
"cheese":{"calcium", "protein"},
"apple":{"sugars", "fiber", "vitamin"} }
total := make(map[string]map[string]bool)
f := bufio.NewScanner(os.Stdin)
currentRecipe := ""
for f.Scan() {
Line(f.Text(), currentRecipe, nutriments, total)
}
fmt.Println(total)
}
func Line (line, currentRecipe string, nut map[string][]string, tot map[string]map[string]bool) {
if foundrec, _ := regexp.MatchString("^# [[:graph:]]+", line); foundrec { // Begin recipe
currentRecipe := line[2:]
fmt.Println("---------", currentRecipe) // update current
tot[currentRecipe] = make(map[string]bool) // <== INITIALIZE SET (1)
}
if foundnut, _ := regexp.MatchString("^- [[:graph:]]+", line); foundnut { // New ingredient
nutri := line[2:]
tot[currentRecipe][nutri] = true // <===== HERE (2)
}
}
浮云间
相关分类