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
+4.9k Golang : List all packages and search for certain package
+12.7k Golang : convert rune to unicode hexadecimal value and back to rune character
+27.9k Golang : missing Git command
+18k Golang : How to run your code only once with sync.Once object
+9.8k Golang : Natural string sorting example
+12k Golang : Calculate elapsed years or months since a date
+16.7k Golang : Convert IPv4 address to decimal number(base 10) or integer
+7.4k Golang : On lambda, anonymous, inline functions and function literals
+7.9k Golang : io.Reader causing panic: runtime error: invalid memory address or nil pointer dereference
+13.3k Golang : Parsing or breaking down URL
+15.8k Golang : XML to JSON example
+15.9k Golang : Check if IP address is version 4 or 6