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

我正在尝试将一个简单的降价文件转换为 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"

        ]

    }

]

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


肥皂起泡泡
浏览 176回答 1
1回答

呼啦一阵风

在for循环内部,仔细看看这部分:// If it's a blank lineif rgxRoot.MatchString(linetext) {&nbsp; &nbsp; rule := &Section{} // Notice the `:=`&nbsp; &nbsp; rule.Category = linetext}您基本上是rule在 that 范围内创建一个新变量if,而您可能想重用已在for循环外创建的变量。因此,尝试将其更改为:// If it's a blank lineif rgxRoot.MatchString(linetext) {&nbsp; &nbsp; rule = &Section{} // Notice the `=`&nbsp; &nbsp; rule.Category = linetext}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go