Menu Close

Go – Remove() function in list package in go golang

In this tutorial, we are going to learn about Remove() function in list package in go golang. Remove() function is used to remove element from the list in go golang.

Function proto type:

func (l *List) Remove(ele *Element) interface{} 

Remove() function:

Remove() function remove element from list. It returns deleted element value.  

Example:

list = 1 -> 2 -> 3 -> 4

Remove element with value 3

list.Remove(3)

list = 1 -> 2 -> 4

To learn more about list package in go, Please follow this link

Example to use Remove() function in list:

package main

import (
  "container/list"
  "fmt"
)

func main() {
    
  var ele *list.Element

  // Create list and insert elements in it.
  list_1 := list.New()

  list_1.PushBack(1) // 1
  list_1.PushBack(2) // 1 -> 2
  list_1.PushBack(3) // 1 -> 2 -> 3
  list_1.PushBack(4) // 1 -> 2 -> 3 -> 4

  fmt.Println("Print list_1")
  for ele = list_1.Front(); ele != nil; ele = ele.Next() {

    fmt.Println(ele.Value)
    
  }

  // remove element with value 3
  for ele = list_1.Front(); ele.Value != 3; ele = ele.Next() { }

  list_1.Remove(ele)

  fmt.Println("Print list_1 after deleting elemenet: ")
  for ele = list_1.Front(); ele != nil; ele = ele.Next() {

    fmt.Println(ele.Value)
  }
}

Output:

Print list_1
1
2
3
4
Print list_1 after deleting elemenet:
1
2
4

To learn more about golang, Please refer given below link:

https://techieindoor.com/go-lang-tutorial/
https://techieindoor.com/go-lang-tutorial/

References:

https://golang.org/doc/
https://golang.org/pkg/
https://golang.org/pkg/fmt/
https://golang.org/pkg/fmt/#Println
https://golang.org/pkg/container/list/
Posted in golang, list package

Leave a Reply

Your email address will not be published. Required fields are marked *