2

Is it possible to iterate on a golang array/slice without using 'for' statement?

2
  • 2
    I 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. Commented Dec 17, 2015 at 3:55
  • Does this answer your question? See stackoverflow.com/a/64276054/12817546. Commented Oct 9, 2020 at 8:05

4 Answers 4

9

You could use goto statement (not recommended).

package main

import (
    "fmt"
)

func main() {
    my_slice := []string {"a", "b", "c", "d"}

    index := 0

back:
    if index < len(my_slice) {
        fmt.Println(my_slice[index])
        index += 1
        goto back
    }
}
Sign up to request clarification or add additional context in comments.

Comments

2

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

1

You could write a recursive function to iterate over the slice but why would you want to not use a for loop?

3 Comments

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.
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.
0

Go doesn't have different loop keywords like for or while, it just has for which has a few different forms

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.