Home  >  Article  >  Backend Development  >  How to delete elements from list in go language

How to delete elements from list in go language

青灯夜游
青灯夜游Original
2023-01-16 10:59:092623browse

In the Go language, you can use the remove() function to delete list elements. The syntax is "list object.Remove(element)". The parameter element indicates that the list element is to be deleted. The element element cannot be empty. If it is not empty, the value of the deleted element will be returned. If it is empty, an exception will be reported.

How to delete elements from list in go language

The operating environment of this tutorial: Windows 7 system, GO version 1.18, Dell G3 computer.

go provides a list package, similar to python's list, which can store any type of data and provides the corresponding API, as follows:

type Element
    func (e *Element) Next() *Element
    func (e *Element) Prev() *Element
type List
    func New() *List
    func (l *List) Back() *Element
    func (l *List) Front() *Element
    func (l *List) Init() *List
    func (l *List) InsertAfter(v interface{}, mark *Element) *Element
    func (l *List) InsertBefore(v interface{}, mark *Element) *Element
    func (l *List) Len() int
    func (l *List) MoveAfter(e, mark *Element)
    func (l *List) MoveBefore(e, mark *Element)
    func (l *List) MoveToBack(e *Element)
    func (l *List) MoveToFront(e *Element)
    func (l *List) PushBack(v interface{}) *Element
    func (l *List) PushBackList(other *List)
    func (l *List) PushFront(v interface{}) *Element
    func (l *List) PushFrontList(other *List)
    func (l *List) Remove(e *Element) interface{}

Among them, the remove() function is used for lists Delete elements from list. The deleted elements cannot be empty. If they are empty, an exception will be reported.

Remove(e *Element) interface{}
Parameters Description
e To delete list elements.

Return value

  • Returns the value of the deleted element.

Example of list deletion elements

Example 1:

package main
import (
	"container/list"
	"fmt"
)
func main() {
	//使用 Remove 在列表中删除元素
	listHaiCoder := list.New()
	listHaiCoder.PushFront("Hello")
	listHaiCoder.PushFront("HaiCoder")
	element := listHaiCoder.PushFront("Hello")
	removeEle := listHaiCoder.Remove(element)
	fmt.Println("RemoveElement =", removeEle)
	for i := listHaiCoder.Front(); i != nil; i = i.Next() {
		fmt.Println("Element =", i.Value)
	}
}

How to delete elements from list in go language

Analysis:

  • We created a list listHaiCoder through list.New, then used the PushFront function to insert three elements into the list, and then used the Remove function to delete the last inserted element.

  • Finally, we print the deleted elements and the deleted list. The Remove function returns the value of the deleted element. At the same time, we find that the last inserted element has been successfully removed from List deleted.

Example 2: Delete empty elements

package main
import (
	"container/list"
	"fmt"
)
func main() {
	//使用 Remove 在列表中删除空元素,报错
	listHaiCoder := list.New()
	listHaiCoder.PushFront("Hello")
	listHaiCoder.PushFront("HaiCoder")
	listHaiCoder.Remove(nil)
}

After the program is run, the console output is as follows:

How to delete elements from list in go language

Extended knowledge: list deletes all elements

With the API provided by the list package, the list is indeed very convenient to use, but during use, if you are not careful, you will encounter some pitfalls that are difficult to find. , resulting in program results not being as expected. The pitfall here is the problem encountered when traversing the list through a for loop and deleting all elements. For example, the following sample program creates a list, stores 0-3 in sequence, and then traverses the list to delete all elements through a for loop:

package main
import (
    "container/list"
    "fmt"
)
func main() {
    l := list.New()
    l.PushBack(0)
    l.PushBack(1)
    l.PushBack(2)
    l.PushBack(3)
    fmt.Println("original list:")
    prtList(l)
    fmt.Println("deleted list:")
    for e := l.Front(); e != nil; e = e.Next() {
        l.Remove(e)
    }
    prtList(l)
}
func prtList(l *list.List) {
    for e := l.Front(); e != nil; e = e.Next() {
        fmt.Printf("%v ", e.Value)
    }
    fmt.Printf("n")
}

The output of running the program is as follows:

original list:
0 1 2 3
deleted list:
1 2 3

From It can be seen from the output that the elements in the list have not been completely deleted, only the first element 0 has been deleted, which is different from the original idea. According to the usage habits of Go, the writing method of traversing a list and deleting all elements should be as follows:

for e := l.Front(); e != nil; e = e.Next() {
    l.Remove(e)
}

But according to the output of the above example code, it is invalid to delete all elements of the list. So what is the problem? From the for loop mechanism, we can know that since the first element has been deleted but the second element has not been deleted, it must be that the condition of the second loop is invalid, which causes the loop to exit, that is, after executing the following statement:

l.Remove(e)

e should be nil, so the loop exits. Add a print statement to verify before the l.Remove(e) statement in the for loop. For example, add the following statement:

fmt.Println("delete a element from list")

The output of running the program is as follows:

original list:
0 1 2 3
deleted list:
delete a element from list
1 2 3

You can see that it is indeed only looping Once, the cycle is over. That is, after the statement l.Remove(e) is executed, e is equal to e.Next(). Because e.Next() is nil, e is nil and the loop exits. Why is e.Next() nil? By viewing the go list source code, it is as follows:

// remove removes e from its list, decrements l.len, and returns e.
func (l *List) remove(e *Element) *Element {
    e.prev.next = e.next
    e.next.prev = e.prev
    e.next = nil // avoid memory leaks
    e.prev = nil // avoid memory leaks
    e.list = nil
    l.len--
    return e
}
// Remove removes e from l if e is an element of list l.
// It returns the element value e.Value.
func (l *List) Remove(e *Element) interface{} {
    if e.list == l {
        // if e.list == l, l must have been initialized when e was inserted
        // in l or l == nil (e is a zero Element) and l.remove will crash
        l.remove(e)
    }
    return e.Value
}

It can be seen from the source code that when l.Remove(e) is executed, the l.remove(e) method will be called internally to delete element e. In order To avoid memory leaks, e.next and e.prev will be assigned nil, which is the source of the problem.

The correction procedure is as follows:

package main
import (
    "container/list"
    "fmt"
)
func main() {
    l := list.New()
    l.PushBack(0)
    l.PushBack(1)
    l.PushBack(2)
    l.PushBack(3)
    fmt.Println("original list:")
    prtList(l)
    fmt.Println("deleted list:")
    var next *list.Element
    for e := l.Front(); e != nil; e = next {
        next = e.Next()
        l.Remove(e)
    }
    prtList(l)
}
func prtList(l *list.List) {
    for e := l.Front(); e != nil; e = e.Next() {
        fmt.Printf("%v ", e.Value)
    }
    fmt.Printf("n")
}

The output of running the program is as follows:

original list:
0 1 2 3
deleted list:

As you can see, all elements in the list have been deleted correctly.

【Related recommendations: Go video tutorial, Programming teaching

The above is the detailed content of How to delete elements from list in go language. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn