doutuoben6908 2016-05-22 20:42
浏览 18
已采纳

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

I'm attempting to convert a simple markdown file into json, the markdown looks something like this:

#TITLE 1
- Line 1
- Line 2
- Line 3

#TITLE 2
- Line 1
- Line 2
- Line 3
<!-- blank line -->

I can't understand what's required to refactor the following in 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))

The code above outputs:

[
{
        "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"
        ]
    }
]

When I was hoping to output:

[
    {
        "Category": "#TITLE 1",
        "Lines": [
            "- Line 1",
            "- Line 2",
            "- Line 3"
        ]
    },
    {
        "Category": "#TITLE 2",
        "Lines": [,
            "- Line 1",
            "- Line 2",
            "- Line 3"
        ]
    }
]

Couple of things wrong for sure. Please excuse the verbosity of the question, hard to explain without an example when you're a noob. Thanks in advance.

  • 写回答

1条回答 默认 最新

  • dongtui6347 2016-05-22 21:04
    关注

    Inside the for loop, take a closer look to this part:

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

    You're basically creating a new rule variable in the scope of that if, when you probably want to reuse the one you have already created outside the for loop.

    So, try changing it to:

    // If it's a blank line
    if rgxRoot.MatchString(linetext) {
        rule = &Section{} // Notice the `=`
        rule.Category = linetext
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?