Menu Close

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

In this tutorial, we are going to learn about Next() function in list package in go golang. Next() function is used to get the next element in list go golang.

Next() function proto type:

 func (e *Element) Next() *Element 

Return value of Next():

 Next() returns the next element in list or nil. 

To learn more about list package, Please follow this link

Example to use Next() function in list:

package main

import (
  "container/list"
  "fmt"
)

func main() {
  // Create a new list and insert elements in it.
  l := list.New()
  l.PushBack(1)  // 1
  l.PushBack(2) //  1 -> 2
  l.PushBack(3)  //  1 -> 2 -> 3

  // get the head of the list
  ele := l.Front()
  fmt.Println(ele.Value)

  // get next element of the list
  ele = ele.Next()
  fmt.Println(ele.Value)

  // get next element of the list
  ele = ele.Next()
  fmt.Println(ele.Value)
}

Output:

 1
2
3

Example to use Next() function using for loop:

package main

import (
  "container/list"
  "fmt"
)

func main() {
  // Create a new list and insert elements in it.
  l := list.New()
  l.PushBack(1)  // 1
  l.PushBack(2) //  1 -> 2
  l.PushBack(3)  //  1 -> 2 -> 3

  for ele := l.Front(); ele != nil; ele = ele.Next() {

    fmt.Println(ele.Value)
  }
}

Output:

 1
2
3

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

https://www.techieindoor.com/go-lang-tutorial/
https://www.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 *