Is it possible to iterate on a golang array/slice without using 'for' statement?
-
2I don't think asking "for doing what" is appropriate to this question since the question is so clear that he asked about existence of an alternative way to iterate. He has his purpose.vutran– vutran2015-12-17 03:55:49 +00:00Commented Dec 17, 2015 at 3:55
-
Does this answer your question? See stackoverflow.com/a/64276054/12817546.user12817546– user128175462020-10-09 08:05:25 +00:00Commented Oct 9, 2020 at 8:05
Add a comment
|
4 Answers
As mentioned by @LeoCorrea you could use a recursive function to iterate over a slice. A tail recursion could prevent the stack overflow mentioned by @vutran.
package main
import "fmt"
func num(a []string, i int) {
if i >= len(a) {
return
} else {
fmt.Println(i, a[i]) //0 a 1 b 2 c
i += 1
num(a, i) //tail recursion
}
}
func main() {
a := []string{"a", "b", "c"}
i := 0
num(a, i)
}
A possibly more readable but less pure example could use an anonymous function. See https://play.golang.org/p/Qen6BKviWuE.
Comments
You could write a recursive function to iterate over the slice but why would you want to not use a for loop?
3 Comments
vutran
Warning for anyone who tries to use recursive rather than a
for, don't use recursive for too many loops, it will flood the stack memory causing stack overflow error and stackoverflow.com look up.Leo Correa
Right, this is a good explanation goinggo.net/2013/09/recursion-and-tail-calls-in-go_26.html
Good answer +1. I might want to use a recursive if I wanted to use pure functions with minimal side-effects i.e. functional programming. See stackoverflow.com/a/64276054/12817546.