gpt4 book ai didi

go - 实例化结构和数组不会创建新的引用

转载 作者:数据小太阳 更新时间:2023-10-29 03:06:08 26 4
gpt4 key购买 nike

我正在尝试将一个简单的 markdown 文件转换为 json,markdown 看起来像这样:

#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"
]
}
]

肯定有几处错误。请原谅这个问题的冗长,当你是菜鸟时,没有例子很难解释。提前致谢。

最佳答案

for 循环中,仔细看看这部分:

// If it's a blank line
if rgxRoot.MatchString(linetext) {
rule := &Section{} // Notice the `:=`
rule.Category = linetext
}

您基本上是在 if 的范围内创建一个新的 rule 变量,而您可能想重用您已经在 之外创建的变量for 循环。

因此,尝试将其更改为:

// If it's a blank line
if rgxRoot.MatchString(linetext) {
rule = &Section{} // Notice the `=`
rule.Category = linetext
}

关于go - 实例化结构和数组不会创建新的引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37379450/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com