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
+9k Golang : Build and compile multiple source files
+8.5k Linux/Unix : fatal: the Postfix mail system is already running
+6.8k Golang : Decode XML data from RSS feed
+9.3k Golang : How to protect your source code from client, hosting company or hacker?
+9.2k Golang : Write multiple lines or divide string into multiple lines
+13.6k Android Studio : Password input and reveal password example
+16.9k Golang : Set up source IP address before making HTTP request
+7.2k Golang : Check if one string(rune) is permutation of another string(rune)
+13.1k Golang : Convert(cast) uintptr to string example
+39.6k Golang : Remove dashes(or any character) from string
+4.7k Linux/MacOSX : How to symlink a file?
+14k Golang : convert rune to unicode hexadecimal value and back to rune character