Golang : How to iterate a slice without using for loop?
A very simple example on how to iterate a slice of integers without using a for
loop and use recursive method instead.
package main
import (
"fmt"
)
func main() {
integerSlice := []int{0, 1, 2, 3, 4}
loopIntegerSlice(integerSlice, 0)
}
func loopIntegerSlice(numbers []int, index int) int {
// iterate a slice and print out the elements without using a for loop
if index == len(numbers) {
return numbers[index-1] // break here
} else {
n := numbers[index]
fmt.Println(n)
return loopIntegerSlice(numbers, index+1) // use recursive method
}
}
Output:
0
1
2
3
4
See also : Golang : Find the length of big.Int variable example
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
+21.4k Golang : simulate tail -f or read last line from log file example
+16.3k Google Chrome : Your connection to website is encrypted with obsolete cryptography
+9.5k Golang : Create matrix with Gonum Matrix package example
+22.4k Golang : Check if element exist in map
+4.1k Golang : Display packages names during compilation
+6.1k Golang : Accessing dataframe-go element by row, column and name example
+6.3k Golang : Getting Echo framework StartAutoTLS to work
+22.6k Golang : Generate MD5 checksum of a file
+8k Golang : Serving HTTP and Websocket from different ports in a program example
+17.6k Golang : Populate dropdown with html/template example
+9.6k Golang : Bubble sort example
+8.2k Golang : Read file with ioutil