for init; condition; post {
...
}
-
init
inicia cualquier variable que pueda necesitarse al empezar el bucle o usar al finalizarlo.La declaración puede ser llamada una vez cuando el bucle empieza a ejecutarse.
-
condition
validaciones del estado para una condición.Si la condición devuelve true entonces el código dentro del loop se ejecutará.
-
Al final de la ejecución del código el
post
será ejecutado.En esta ejecución podremos modificar las variables definidas en el
init
. Después de la ejecución en elpost
la condición de estado se volverá a evaluar de nuevo.Si esta evaluación devuelve true, el código dentro del bucle se ejecutará de nuevo, así sucesivamente hasta que el loop termine.
package main
import (
"fmt"
)
func main() {
fmt.Pritln()
fmt.Println("The for loops")
for i := 1; i <= 6; i++ {
fmt.Printf("Current number is %d \n", i)
}
}
/*
// Run this code the console outup is
The for loops
Current number is 1
Current number is 2
Current number is 3
Current number is 4
Current number is 5
Current number is 6
*/
Go permite colocar el init statment y ejecutarlo fuera del loop pero en ese caso la variable estará accesible fuera del loop.
package main
import (
"fmt"
)
func main() {
fmt.Println()
fmt.Println("Optional init statement")
q := 1
for ; q <= 6; q++ {
fmt.Printf("Current number is %d \n", q)
}
}
/*
// Run this code the console outup is
Optional init statement
Current number is 1
Current number is 2
Current number is 3
Current number is 4
Current number is 5
Current number is 6
*/
Go permite colocar y ejecutar dentro del código del bucle el código post para obtener los mismos resultados.
package main
import (
"fmt"
)
func main() {
fmt.Println()
fmt.Println("Optional post statement")
for j := 1; j <= 6; {
fmt.Printf("Current number is %d \n", j)
j++
}
}
/*
// Run this code the console outup is
Optional post statement
Current number is 1
Current number is 2
Current number is 3
Current number is 4
Current number is 5
Current number is 6
*/
Un bucle for puede tener solo la condición que comprueba el statment, extrayendo fuera del bucle el init y ubicando dentro del bucle el post.
package main
import (
"fmt"
)
func main() {
fmt.Println()
fmt.Println("Optional init and post statement")
x := 1
for x <= 6 {
fmt.Printf("Current number is %d \n", x)
x++
}
}
/*
Optional init and post statement
Current number is 1
Current number is 2
Current number is 3
Current number is 4
Current number is 5
Current number is 6
*/
Un bucle for sin init, post o check statetment es un bucle for cuya condition statement siempre es true. Esto quiere decir que estará iterando indefinidamente hasta que sea terminado manualmente dentro del código del bucle. Para esta operación tenemos la palabra reservada break para terminar el loop.
package main
import (
"fmt"
)
func main() {
fmt.Println()
fmt.Println("Without all statements")
y := 1
for {
fmt.Printf("Current number is %d \n", y)
if y == 6 {
break
}
y++
}
}
/*
Optional init and post statement
Without all statements
Current number is 1
Current number is 2
Current number is 3
Current number is 4
Current number is 5
Current number is 6
*/
El break statement es usado dentro del bucle for para terminarlo.
Cualquier código después del break no será ejecutado.
package main
import (
"fmt"
)
func main() {
fmt.Println()
fmt.Println("The break statement ")
for l := 1; l <= 10; l++ {
if l > 6 {
break
}
fmt.Printf("Current number is %d \n", l)
}
}
/*
Optional init and post statement
The break statement
Current number is 1
Current number is 2
Current number is 3
Current number is 4
Current number is 5
Current number is 6
*/
El continue statement es usado para saltar a la siguiente iteracción del bucle for, simplemente:
-
Ignora la iteracción actual
-
Ejecuta el post statment
-
Empieza la siguiente iteracción
package main
import (
"fmt"
)
func main() {
fmt.Println()
fmt.Println("The continue statement")
for f := 1; f <= 10; f++ {
if f%2 != 0 {
continue
}
fmt.Printf("Current number is %d \n", f)
}
}
/*
Optional init and post statement
The continue statement
Current number is 2
Current number is 4
Current number is 6
Current number is 8
Current number is 10
*/
Si el bucle for encuentra return statement, la función de ejecución se parará y el valor será devuelto por la función, por ende podemos decir que el return no es algo específico del bucle for.
package main
import "fmt"
func main() {
/* create a slice */
numbers := []int{0,1,2,3,4,5,6,7,8}
/* print the numbers */
for i:= range numbers {
fmt.Println("Slice item",i,"is",numbers[i])
}
}
package main
import "fmt"
func main() {
/* create a map*/
countryCapitalMap := map[string] string {"France":"Paris","Italy":"Rome","Japan":"Tokyo"}
/* print map using keys*/
for country := range countryCapitalMap {
fmt.Println("Capital of",country,"is",countryCapitalMap[country])
}
}
package main
import "fmt"
func main() {
/* create a map*/
countryCapitalMap := map[string] string {"France":"Paris","Italy":"Rome","Japan":"Tokyo"}
/* print map using key-value*/
for country,capital := range countryCapitalMap {
fmt.Println("Capital of",country,"is",capital)
}
}