nathanos
nathanos

Reputation: 63

Iterate on a golang array/slice without using for statement

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

Upvotes: 2

Views: 5201

Answers (4)

user12817546
user12817546

Reputation:

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.

Upvotes: 2

Peter R
Peter R

Reputation: 414

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

Upvotes: 0

Akavall
Akavall

Reputation: 86306

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
    }
}

Upvotes: 9

Leo Correa
Leo Correa

Reputation: 19829

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

Upvotes: 1

Related Questions