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
+9.7k Golang : Random Rune generator
+6.7k Javascript : How to get JSON data from another website with JQuery or Ajax ?
+4.7k Swift : Convert (cast) Float to Int or Int32 value
+29.8k Golang : Generate random string
+8.3k Golang : Accept any number of function arguments with three dots(...)
+17.6k Golang : Get command line arguments
+14.3k Golang : Save(pipe) HTTP response into a file
+6.7k Golang : Null and nil value
+5.4k Unix/Linux : How to test user agents blocked successfully ?
+10.6k Golang : Calculate Relative Strength Index(RSI) example
+9.7k Golang : Text file editor (accept input from screen and save to file)
+7k Golang : Convert source code to assembly language