search
HomeBackend DevelopmentGolangHow to delete elements from list in go language

How to delete elements from list in go language

Jan 16, 2023 am 10:59 AM
golanggo 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{}

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
Type Assertions and Type Switches with Go InterfacesType Assertions and Type Switches with Go InterfacesMay 02, 2025 am 12:20 AM

Gohandlesinterfacesandtypeassertionseffectively,enhancingcodeflexibilityandrobustness.1)Typeassertionsallowruntimetypechecking,asseenwiththeShapeinterfaceandCircletype.2)Typeswitcheshandlemultipletypesefficiently,usefulforvariousshapesimplementingthe

Using errors.Is and errors.As for Error Inspection in GoUsing errors.Is and errors.As for Error Inspection in GoMay 02, 2025 am 12:11 AM

Go language error handling becomes more flexible and readable through errors.Is and errors.As functions. 1.errors.Is is used to check whether the error is the same as the specified error and is suitable for the processing of the error chain. 2.errors.As can not only check the error type, but also convert the error to a specific type, which is convenient for extracting error information. Using these functions can simplify error handling logic, but pay attention to the correct delivery of error chains and avoid excessive dependence to prevent code complexity.

Performance Tuning in Go: Optimizing Your ApplicationsPerformance Tuning in Go: Optimizing Your ApplicationsMay 02, 2025 am 12:06 AM

TomakeGoapplicationsrunfasterandmoreefficiently,useprofilingtools,leverageconcurrency,andmanagememoryeffectively.1)UsepprofforCPUandmemoryprofilingtoidentifybottlenecks.2)Utilizegoroutinesandchannelstoparallelizetasksandimproveperformance.3)Implement

The Future of Go: Trends and DevelopmentsThe Future of Go: Trends and DevelopmentsMay 02, 2025 am 12:01 AM

Go'sfutureisbrightwithtrendslikeimprovedtooling,generics,cloud-nativeadoption,performanceenhancements,andWebAssemblyintegration,butchallengesincludemaintainingsimplicityandimprovingerrorhandling.

Understanding Goroutines: A Deep Dive into Go's ConcurrencyUnderstanding Goroutines: A Deep Dive into Go's ConcurrencyMay 01, 2025 am 12:18 AM

GoroutinesarefunctionsormethodsthatrunconcurrentlyinGo,enablingefficientandlightweightconcurrency.1)TheyaremanagedbyGo'sruntimeusingmultiplexing,allowingthousandstorunonfewerOSthreads.2)Goroutinesimproveperformancethrougheasytaskparallelizationandeff

Understanding the init Function in Go: Purpose and UsageUnderstanding the init Function in Go: Purpose and UsageMay 01, 2025 am 12:16 AM

ThepurposeoftheinitfunctioninGoistoinitializevariables,setupconfigurations,orperformnecessarysetupbeforethemainfunctionexecutes.Useinitby:1)Placingitinyourcodetorunautomaticallybeforemain,2)Keepingitshortandfocusedonsimpletasks,3)Consideringusingexpl

Understanding Go Interfaces: A Comprehensive GuideUnderstanding Go Interfaces: A Comprehensive GuideMay 01, 2025 am 12:13 AM

Gointerfacesaremethodsignaturesetsthattypesmustimplement,enablingpolymorphismwithoutinheritanceforcleaner,modularcode.Theyareimplicitlysatisfied,usefulforflexibleAPIsanddecoupling,butrequirecarefulusetoavoidruntimeerrorsandmaintaintypesafety.

Recovering from Panics in Go: When and How to Use recover()Recovering from Panics in Go: When and How to Use recover()May 01, 2025 am 12:04 AM

Use the recover() function in Go to recover from panic. The specific methods are: 1) Use recover() to capture panic in the defer function to avoid program crashes; 2) Record detailed error information for debugging; 3) Decide whether to resume program execution based on the specific situation; 4) Use with caution to avoid affecting performance.

See all articles

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

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.