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

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

實例化結構和數組不會創建新的引用

實例化結構和數組不會創建新的引用

Go
肥皂起泡泡 2022-01-10 18:50:37
我正在嘗試將一個簡單的降價文件轉換為 json,降價看起來像這樣:#TITLE 1- Line 1- Line 2- Line 3#TITLE 2- Line 1- Line 2- Line 3<!-- blank line -->我不明白在func main() 中重構以下內容需要什么:    type Section struct {        Category string        Lines    []string    }    file, _ := os.Open("./src/basicmarkdown/basicmarkdown.md")    defer file.Close()    rgxRoot, _ := regexp.Compile("^#[^#]")    rgxBehaviour, _ := regexp.Compile("^-[ ]?.*")    scanner := bufio.NewScanner(file)    ruleArr := []*Section{}    rule := &Section{}    for scanner.Scan() {        linetext := scanner.Text()        // If it's a blank line        if rgxRoot.MatchString(linetext) {            rule := &Section{}            rule.Category = linetext        }        if rgxBehaviour.MatchString(linetext) {            rule.Lines = append(rule.Lines, linetext)        }        if len(strings.TrimSpace(linetext)) == 0 {            ruleArr = append(ruleArr, rule)        }    }    jsonSection, _ := json.MarshalIndent(ruleArr, "", "\t")    fmt.Println(string(jsonSection))上面的代碼輸出:[{        "Category": "",        "Lines": [            "- Line 1",            "- Line 2",            "- Line 3",            "- Line 1",            "- Line 2",            "- Line 3"        ]    },    {        "Category": "",        "Lines": [            "- Line 1",            "- Line 2",            "- Line 3",            "- Line 1",            "- Line 2",            "- Line 3"        ]    }]當我希望輸出時:[    {        "Category": "#TITLE 1",        "Lines": [            "- Line 1",            "- Line 2",            "- Line 3"        ]    },    {        "Category": "#TITLE 2",        "Lines": [,            "- Line 1",            "- Line 2",            "- Line 3"        ]    }]肯定有幾件事是錯的。請原諒這個問題的冗長,當你是一個菜鳥時,如果沒有例子就很難解釋。提前致謝。
查看完整描述

1 回答

?
呼啦一陣風

TA貢獻1802條經驗 獲得超6個贊

在for循環內部,仔細看看這部分:


// If it's a blank line

if rgxRoot.MatchString(linetext) {

    rule := &Section{} // Notice the `:=`

    rule.Category = linetext

}

您基本上是rule在 that 范圍內創建一個新變量if,而您可能想重用已在for循環外創建的變量。


因此,嘗試將其更改為:


// If it's a blank line

if rgxRoot.MatchString(linetext) {

    rule = &Section{} // Notice the `=`

    rule.Category = linetext

}


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

添加回答

舉報

0/150
提交
取消
微信客服

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

幫助反饋 APP下載

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

公眾號

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