Go/Lists
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
| Go notes on Go
Go/Strings · Go/Arrays · Go/Slices
Go/Lists · Go/Maps · Go/Stacks · Go/Queues
Go/Naming Conventions · Go/Design Patterns
Go/Timing · Go/Profiling · Go/Benchmarking
Go/Tests · Go/Travis CI · Go/Makefiles
our vim + go setup uses custom solarized colors for Golang
|