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

How to delete elements from list in go language

Jan 16, 2023 am 10:59 AM
golang go language

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{}
Copy after login

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{}
Copy after login
ParametersDescription
eTo 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)
	}
}
Copy after login

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)
}
Copy after login

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")
}
Copy after login

The output of running the program is as follows:

original list:
0 1 2 3
deleted list:
1 2 3
Copy after login

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)
}
Copy after login

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)
Copy after login

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")
Copy after login

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
Copy after login

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
}
Copy after login

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")
}
Copy after login

The output of running the program is as follows:

original list:
0 1 2 3
deleted list:
Copy after login

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 of this Website
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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

What libraries are used for floating point number operations in Go? What libraries are used for floating point number operations in Go? Apr 02, 2025 pm 02:06 PM

The library used for floating-point number operation in Go language introduces how to ensure the accuracy is...

What is the problem with Queue thread in Go's crawler Colly? What is the problem with Queue thread in Go's crawler Colly? Apr 02, 2025 pm 02:09 PM

Queue threading problem in Go crawler Colly explores the problem of using the Colly crawler library in Go language, developers often encounter problems with threads and request queues. �...

What should I do if the custom structure labels in GoLand are not displayed? What should I do if the custom structure labels in GoLand are not displayed? Apr 02, 2025 pm 05:09 PM

What should I do if the custom structure labels in GoLand are not displayed? When using GoLand for Go language development, many developers will encounter custom structure tags...

How to solve the user_id type conversion problem when using Redis Stream to implement message queues in Go language? How to solve the user_id type conversion problem when using Redis Stream to implement message queues in Go language? Apr 02, 2025 pm 04:54 PM

The problem of using RedisStream to implement message queues in Go language is using Go language and Redis...

In Go, why does printing strings with Println and string() functions have different effects? In Go, why does printing strings with Println and string() functions have different effects? Apr 02, 2025 pm 02:03 PM

The difference between string printing in Go language: The difference in the effect of using Println and string() functions is in Go...

In Go programming, how to correctly manage the connection and release resources between Mysql and Redis? In Go programming, how to correctly manage the connection and release resources between Mysql and Redis? Apr 02, 2025 pm 05:03 PM

Resource management in Go programming: Mysql and Redis connect and release in learning how to correctly manage resources, especially with databases and caches...

Which libraries in Go are developed by large companies or provided by well-known open source projects? Which libraries in Go are developed by large companies or provided by well-known open source projects? Apr 02, 2025 pm 04:12 PM

Which libraries in Go are developed by large companies or well-known open source projects? When programming in Go, developers often encounter some common needs, ...

Golang's Purpose: Building Efficient and Scalable Systems Golang's Purpose: Building Efficient and Scalable Systems Apr 09, 2025 pm 05:17 PM

Go language performs well in building efficient and scalable systems. Its advantages include: 1. High performance: compiled into machine code, fast running speed; 2. Concurrent programming: simplify multitasking through goroutines and channels; 3. Simplicity: concise syntax, reducing learning and maintenance costs; 4. Cross-platform: supports cross-platform compilation, easy deployment.

See all articles