DEV Community

loading...
Cover image for Golang basic: looping

Golang basic: looping

shellrean profile image ShellRean ・2 min read

You wake up and look at the clock and woo it's late to go to work. its always happen to you and make it as daily activity.
it will repeat the same thing but you can change that until something happen, stop and never happen again.

Is a simple concept of looping doing something until you decide to stop you want to stop until a condition is happen.

Write simple code loop

Golang has only have a loop it is for loop lets we code

package main

import "fmt"

func main() {
    for i := 0; i < 10; i++ {
        fmt.Printf("Loop in number %d\n", i)
    }
}
Enter fullscreen mode Exit fullscreen mode

We can write loop from 0 (i := 0), and make a condition i<10, if the condition is not true looping will be stop. Increase the variable i i++ so the the loop will stop.

Loop iteration data type

Now the condition is what happen if we want to get value of slice? we can create like below.

package main

import "fmt"

func main() {
    fruits := []string{"banana","watermelon","apple","coconut"}

    for i := 0; i < len(fruits); i++ {
        fmt.Printf("Fruit index %d is %s\n", i, fruits[i])
    }
}
Enter fullscreen mode Exit fullscreen mode

We create loop i until i have value less than 4. and we get fruit at index of i, but it is not a best practice, we know that we can use range instead.

package main

import "fmt"

func main() {
    fruits := []string{"banana","watermelon","apple","coconut"}

    for i, item := range fruits {
        fmt.Printf("Fruit index %d is %s\n", i, item)
    }
}
Enter fullscreen mode Exit fullscreen mode

Nested loop

Imagine we want to create coordinate that have latitude and longitude. We can create is nested as below.

package main

import "fmt"

func main() {
    for i := 0; i < 10; i++ {
        for j := 0; j < 20; j++ {
            fmt.Printf("%d%d ",i,j)
        }
        fmt.Println()
    }
}
Enter fullscreen mode Exit fullscreen mode

Infinity loop

How if we don't know when we should stop the loop. we can use infinity loop, but the question is how to stop infinity loop? actually loop it will stop manually using key break like below.

package main

import "fmt"

func main() {
    for true {
        fmt.Printf("Infinity loop")
        break
    }
}
Enter fullscreen mode Exit fullscreen mode

Conclusion

Now we know about loop so you can write "I will not do that again" 100 times without write it until 100 manually.

Discussion (0)

pic
Editor guide