From charlesreid1

(Created page with "To use lists in Go, use the "container/lists" package. This will import a linked list object. <code>import "container/list"</code> Link: https://golang.org/pkg/container/list...")
 
 
(3 intermediate revisions by the same user not shown)
Line 2: Line 2:


Link: https://golang.org/pkg/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:


<pre>
<pre>
package main
package main


import "container/list"
import (
    "fmt"
    "container/list"
)


func main() {
func main() {


     // Initialize list
     // 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
     // Iterate over list
     for e := l.Front(); e != nil; e = e.Next() {
     for e := l.Front(); e != nil; e = e.Next() {
// do something with e.Value
fmt.Println(e.Value)
     }
     }
}
}
</pre>
</pre>
=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=
=Flags=


{{GoFlag}}
{{GoFlag}}

Latest revision as of 14:45, 13 December 2018

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