为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

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 关注
  • 175 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号