golang-切片中指针的内容在递归函数运行期间发生更改 [英] golang - Content of a pointer in a slice changes during recursive function run

查看:169
本文介绍了golang-切片中指针的内容在递归函数运行期间发生更改的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

func getAllCertainDivs(className string, idName string, htmlTag *HtmlTag, matchingDivs *[]*HtmlTag) {
    fmt.Println(htmlTag.Class)
    if htmlTag.XMLName.Local == "div" {
        if htmlTag.Class == className && htmlTag.Id == idName {
            *matchingDivs = append(*matchingDivs, htmlTag)
        }
    }

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

在上面的函数中,如您所见,我将切片的指针传递给getAllCertainDivs函数.在某个点,将HtmlTag指针推入切片matchingDivs中.在append之后,在让函数再次递归调用自身之前,我检查了matchingDiv切片的内容.然后在if所在的append下面,该函数递归调用一次.我在fmt.Println(htmlTag.Class)停下来,再次检查matchingDivs切片的内容.而且内容与以前完全不同.

In the function above, as you can see, I pass a pointer of a slice into the getAllCertainDivs function. At a point a HtmlTag pointer is pushed into the slice matchingDivs. After the append I check the content of the matchingDiv slice, before letting the function call itself recursively again. Then below the if where append was made, the function calls itself recursively one time. And I stop at the fmt.Println(htmlTag.Class) and check the content of matchingDivs slice again. And the content is completely different than before.

只有一个append,内容如何更改?每次我将其传递到下一个递归调用时,golang是否使用相同的HtmlTag指针?

There has only been one append, how can the content change ? Does golang use the same HtmlTag pointer, everytime I pass it into next recursive call ?

推荐答案

tag变量在循环开始时声明一次,并且tag的值在每次迭代时均被覆盖.这是您在常见问题解答中看到的与以下问题相同的问题:

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)
}

这篇关于golang-切片中指针的内容在递归函数运行期间发生更改的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆