Is it possible to iterate on a golang array/slice without using 'for' statement?
You could write a recursive function to iterate over the slice but why would you want to not use a for
loop?
I also don't understand why you'd want to do this, but here is a code sample using no for
loops.
package main
import "fmt"
type P struct {
Next *P
}
func (p *P) Iterate() *P {
if p.Next != nil {
fmt.Println("Saw another P")
return p.Next.Iterate()
}
return nil
}
func main() {
var z []*P
z = append(z, &P{})
z = append(z, &P{Next: z[len(z)-1]})
z = append(z, &P{Next: z[len(z)-1]})
z = append(z, &P{Next: z[len(z)-1]})
z = append(z, &P{Next: z[len(z)-1]})
z[len(z)-1].Iterate()
}
https://play.golang.org/p/CMSp6M00kR
Please note that, while it contains a slice as requested, the properties of the slice itself go completely unused.
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
}
}
Go doesn't have different loop keywords like for
or while
, it just has for
which has a few different forms