Golang has no other looping option more then for loop like other programming languages.
FOR LOOP
package main import "fmt" func main() { // first part initialization i:=0 second part condition i<3 third part incrementation i=i+1 for i := 0; i < 3; i++ { fmt.Println(i) } //scope of "i" is limited to the loop. That's why this bellow does not work // fmt.Println(i) }
USAGE AS A WHILE LOOP
package main import "fmt" func main() { i := 1 // for i < 3 { // i is in first time is 1 // make some multiplication i = i*2 i *= 2 } fmt.Println(i) // output 4 (1*2*2) }
INFINITE LOOP
package main import "fmt" func main() { i := 1 // for { //actually there is no limitation so loops infinite i++ // incrementation same as i = i+1 // we can brake loop using a condition like below if i == 3{ brake // when i is 3 brake the loop } } fmt.Println(i) // output 3 }
CONTINUE
package main import "fmt" func main() { for i := 0; i <= 10; i++ { //if i is a odd number continue "jump" if i%2 != 0 { continue } fmt.Println(i) } }
FOR EACH IN RANGE LOOP
package main import "fmt" func main() { // Array with 3 elements STRING myArray := [3]string{"this is index zero", "this is index one ", "this is index three"} // i for index v for value of array in range of myArray for i, v := range myArray { // print index and value fmt.Println(i, v) } }