From charlesreid1

To use lists in Go, use the "container/lists" package. This will import a linked list object. import "container/list"

Link: https://golang.org/pkg/container/list/

Examples

Basic Example

in the following basic example, we create a new list, populate it, and iterate over it with a for loop to print out its elements:

package main

import (
    "fmt"
    "container/list"
)

func main() {

    // Initialize list
    l := list.New()

    // Populate list
    e4 := l.PushBack(4)
    e1 := l.PushFront(1)

    // State of list is [1, 4]

    l.InsertBefore(3, e4)
    l.InsertAfter(2, e1)

    // State of list is [1, 2, 3, 4]

    // Iterate over list
    for e := l.Front(); e != nil; e = e.Next() {
	fmt.Println(e.Value)
    }
}

Useful Built-In List Methods

There are several built-in methods for lists (see full list here: https://golang.org/pkg/container/list/). These include:

  • Back()
  • Front()
  • Init()
  • Len()
  • PushBack()
  • PushFront()

If we are iterating over a list and are using Front() and Back() to get references to specific elements, the list element objects also have two built-in methods:

  • Next()
  • Prev()

These methods are available via the element object itself and yield new element objects.

Flags