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