Golang : Iterating Elements Over A List
In this short tutorial, we will learn how to iterate the elements over a list. The code below will populate the list first and then perform a "next" scan and then a "prev" scan to list out the elements inside the list.
package main
import (
"container/list"
"fmt"
)
func main() {
alist := list.New()
alist.PushBack("a")
alist.PushBack("b")
alist.PushBack("c")
fmt.Println("Next")
for e := alist.Front(); e != nil; e = e.Next() {
fmt.Println(e.Value) // print out the elements
}
fmt.Println("---------")
fmt.Println("Prev")
for e := alist.Back(); e != nil; e = e.Prev() {
fmt.Println(e.Value) // print out the elements
}
}
Output :
Next
a
b
c
---------
Prev
c
b
a
By Adam Ng
IF you gain some knowledge or the information here solved your programming problem. Please consider donating to the less fortunate or some charities that you like. Apart from donation, planting trees, volunteering or reducing your carbon footprint will be great too.
Advertisement
Tutorials
+7.3k Python : Fix SyntaxError: Non-ASCII character in file, but no encoding declared
+9.8k Golang : Calculate Relative Strength Index(RSI) example
+29.4k Golang : bufio.NewReader.ReadLine to read file line by line
+9.1k Golang : How to tokenize source code with text/scanner package?
+19.8k Golang : Convert string slice to struct and access with reflect example
+10.7k Golang : Clean formatting/indenting or pretty print JSON result
+14.4k Chrome : ERR_INSECURE_RESPONSE and allow Chrome browser to load insecure content
+10.7k Golang : Perform sanity checks on filename example
+32.4k Golang : How to check if slice or array is empty?
+81.3k Golang : How to convert character to ASCII and back
+9.5k Golang : How to unmarshal JSON inner/nested value and assign to specific struct?
+28k Golang : How to declare kilobyte, megabyte, gigabyte, terabyte and so on?