golang - Content of a pointer in a slice changes during recursive function run

后端 未结 1 450
func getAllCertainDivs(className string, idName string, htmlTag *HtmlTag, matchingDivs *[]*HtmlTag) {
    fmt.Println(htmlTag.Class)
    if htmlTag.XMLName.Local == \"di         


        
相关标签:
1条回答
  • 2021-01-28 07:36

    The tag variable is declared once at the start of the loop, and the value of tag is overwritten on each iteration. This is the same problem you see in the FAQ with: "What happens with closures running as goroutines?"

    You can declare a new variable during each iteration to get a unique pointer for the function call:

    for _, tag := range htmlTag.ChildTags {
        tag := tag
        getAllCertainDivs(className, idName, &tag, matchingDivs)
    }
    

    Alternatively you can elide the range value, and use the index directly:

    for i := range htmlTag.ChildTags {
        getAllCertainDivs(className, idName, &htmlTag.ChildTags[i], matchingDivs)
    }
    
    0 讨论(0)
提交回复
热议问题