¿Hay un bucle foreach en Go?


¿Hay una construcción foreach en el idioma Go? ¿Puedo iterar sobre un sector o matriz usando un for?

Author: Altenrion, 2011-10-16

7 answers

Http://golang.org/doc/go_spec.html#For_statements

Una instrucción " for "con una cláusula "range" itera a través de todas las entradas de un array, slice, string o map, o valores recibidos en un canal. Para cada entrada asigna valores de iteración a la iteración correspondiente variables 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.

 615
Author: davetron5000,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-05-17 01:56:01

Iterar sobre array o slice :

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

Itera sobre un canal :

for v := range theChan {}

Iterar sobre un canal equivale a recibir desde un canal hasta que se cierra:

for {
    v, ok := <-theChan
    if !ok {
        break
    }
}
 89
Author: Moshe Revah,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-04-18 21:49:28

El siguiente ejemplo muestra cómo usar el operador range en un bucle for para implementar un bucle foreach.

func PrintXml (out io.Writer, value interface{}) error {
    var data []byte
    var err error

    for _, action := range []func() {
        func () { data, err = xml.MarshalIndent(value, "", "  ") },
        func () { _, err = out.Write([]byte(xml.Header)) },
        func () { _, err = out.Write(data) },
        func () { _, err = out.Write([]byte("\n")) }} {
        action();
        if err != nil {
            return err
        }
    }
    return nil;
}

El ejemplo itera sobre una matriz de funciones para unificar el manejo de errores para las funciones. Un ejemplo completo está en Googles playground .

PD: también muestra que las llaves colgantes son una mala idea para la legibilidad del código. Pista: la condición for termina justo antes de la llamada action(). Obvio, ¿no?

 10
Author: ceving,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-07-07 09:15:48

De hecho, puede usar range sin hacer referencia a sus valores de retorno utilizando for range contra 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++
}

Https://play.golang.org/p/XHrHLbJMEd

 9
Author: robstarbuck,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-09-05 17:32:26

A continuación se muestra el código de ejemplo para 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

 7
Author: Nisal Edu,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-10-03 05:33:06

Esto puede ser obvio, pero puede insertar la matriz de la siguiente manera:

package main

import (
    "fmt"
)

func main() {
    for _, element := range [3]string{"a", "b", "c"} {
        fmt.Print(element)
    }
}

Salidas:

abc

Https://play.golang.org/p/gkKgF3y5nmt

 0
Author: jpihl,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-05-25 12:45:58

Rango :

La forma de rango del bucle for itera sobre un segmento o mapa.

Cuando se extiende sobre un segmento, se devuelven dos valores para cada iteración. El primero es el índice, y el segundo es una copia del elemento en ese índice.

Ejemplo:

package main

import "fmt"

var pow = []int{1, 2, 4, 8, 16, 32, 64, 128}

func main() {
    for i, v := range pow {
        fmt.Printf("2**%d = %d\n", i, v)
    }

    for i := range pow {
        pow[i] = 1 << uint(i) // == 2**i
    }
    for _, value := range pow {
        fmt.Printf("%d\n", value)
    }
}
  • Puede omitir el índice o el valor asignando a _.
  • Si solo desea el índice, elimine el valor , por completo.
 0
Author: FullStack,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-08-15 06:58:10