This article is reproduced
When using Go's Container/list package, you may accidentally step on a small hole, that is, the list of the loop delete elements.
List delete element, the code that intuitively writes down is as follows:
Package Mainimport ("container/list" "FMT") Func main () {//Initialize a listL: =list. New () L.pushback (1) L.pushback (2) L.pushback (3) L.pushback (4) fmt. Println ("before removing ...") //Traverse List, delete element forE: = L.front (); E! = nil; E =E.next () {fmt. Println ("removing", E.value) L.remove (e)} fmt. Println ("After removing ...") //iterate through the list after the element is deleted forE: = L.front (); E! = nil; E =E.next () {fmt. Println (E.value)}}
The above code is very simple, according to common sense, should be able to get the correct results, the list will eventually be emptied. But that is not the case at all, and the results are as follows:
1 After removing ... 2 3 4
As you can see from the results, the list is not emptied at all, but only the first element is deleted. Why is this? The reason for this is the implementation of the Container/list package. This is supposed to be the simplest list I've ever seen, and going out of the comments 100来 the line implementation code, and it's not just a simple list, but it can be used as a stack, as a queue.
The following is the code for the Remove method:
// Remove removes E from the its list, decrements L.len, and returns E. Func (L *list) remove (e *element) *Element { = e.next = e.prev // Avoid memory leaks // Avoid memory leaks e.list = Nil l.len-- return e}
The reason for this problem is obvious, and it appears on the line of code E.next = nil. When playing Remove,e.next it becomes a nil,list traversal and of course it terminates. To find out the cause of the problem, we can easily find the workaround method, the E.next with the intermediate variables to save the OK, the code is as follows:
Package Mainimport ("container/list" "FMT") Func main () {L:=list. New () L.pushback (1) L.pushback (2) L.pushback (3) L.pushback (4) fmt. Println ("before removing ...") varn *list. Element forE: = L.front (); E! = nil; E =N {fmt. Println ("removing", E.value) n=E.next () L.remove (e)} fmt. Println ("After removing ...") forE: = L.front (); E! = nil; E =E.next () {fmt. Println (E.value)}}
The results of the implementation are as follows:
1234afterremoving ...
Reprint Address: http://ju.outofmemory.cn/entry/79972
Go language starting from zero (iii)--list Loop delete Element (reprint)