亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

集合初始化映射(轉圍)

集合初始化映射(轉圍)

Go
千巷貓影 2022-09-26 15:46:04
下面的Gorang代碼根據以下形式的輸入為每個食譜收集了一組營養:# applepie- flour- apple- egg# pizza- flour- cheese- egg- tomato它在 (2) 中抱怨。assignment to entry in nil map但是為什么?然而,每個“子映射”都初始化為 at (1) ?makepackage mainimport (    "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)    }}
查看完整描述

1 回答

?
浮云間

TA貢獻1829條經驗 獲得超4個贊

正如評論所指出的,問題在于當前Recipe的更新機制。字符串按值傳遞。


這是正確的代碼


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() {

            currentRecipe = Line(f.Text(), currentRecipe, nutriments, total)

    }

    fmt.Println(total)

}


func Line (line, currentRecipe string, nut map[string][]string, tot map[string]map[string]bool) string {

    if foundrec, _ := regexp.MatchString("^# [[:graph:]]+", line); foundrec { // Begin recipe

            currentRecipe = line[2:]

            fmt.Println("---------", currentRecipe) // update current

            tot[currentRecipe] = make(map[string]bool) // prepare set

    }

    if foundnut, _ := regexp.MatchString("^- [[:graph:]]+", line); foundnut { // Begin ingredients list

            nutri := line[2:]

            tot[currentRecipe][nutri] = true

    }

    return currentRecipe

}


查看完整回答
反對 回復 2022-09-26
  • 1 回答
  • 0 關注
  • 81 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號