go - for - recorrer array javascript each
¿Hay un bucle foreach en Go? (5)
¿Hay una construcción foreach
en el lenguaje Go? ¿Puedo iterar sobre una porción o matriz usando un for
?
A continuación se muestra el código de ejemplo de cómo usar foreach en golang
package main
import (
"fmt"
)
func main() {
arrayOne := [3]string{"Apple", "Mango", "Banana"}
for index,element := range arrayOne{
fmt.Println(index)
fmt.Println(element)
}
}
Este es un ejemplo en ejecución https://play.golang.org/p/LXptmH4X_0
De hecho, puede usar el range
sin hacer referencia a sus valores de retorno utilizando el for range
su tipo:
arr := make([]uint8, 5)
i,j := 0,0
for range arr {
fmt.Println("Array Loop",i)
i++
}
for range "bytes" {
fmt.Println("String Loop",j)
j++
}
Esto puede ser obvio, pero puede alinear la matriz de esta manera:
package main
import (
"fmt"
)
func main() {
for _, element := range [3]string{"a", "b", "c"} {
fmt.Print(element)
}
}
salidas:
abc
Iterar sobre matriz o sector:
// index and value
for i, v := range slice {}
// index only
for i := range slice {}
// value only
for _, v := range slice {}
Iterar sobre un mapa :
// key and value
for key, value := range theMap {}
// key only
for key := range theMap {}
// value only
for _, value := range theMap {}
Iterar sobre un canal :
for v := range theChan {}
Iterar sobre un canal es equivalente a recibir desde un canal hasta que se cierre:
for {
v, ok := <-theChan
if !ok {
break
}
}
http://golang.org/doc/go_spec.html#For_statements
Una declaración "para" con una cláusula de "rango" se repite en todas las entradas de una matriz, segmento, cadena o mapa, o valores recibidos en un canal. Para cada entrada, asigna valores de iteración a las variables de iteración correspondientes y luego ejecuta el bloque.
Como ejemplo:
for index, element := range someSlice {
// index is the index where we are
// element is the element from someSlice for where we are
}
Si no te importa el índice, puedes usar _
:
for _, element := range someSlice {
// element is the element from someSlice for where we are
}
El subrayado, _
, es el identificador en blanco , un marcador de posición anónimo.