Skip to main content

Command Palette

Search for a command to run...

Loop Init, Condition, Post

Updated
1 min readView as Markdown
Loop  Init, Condition, Post
S
DevRel at StackGen | Formerly at Deepfence ,Tenable , Accurics | AWS Community Builder also Docker Community Award Winner at Dockercon2020 | CyberSecurity Innovator of Year 2023 award by Bsides Bangalore | Docker/HashiCorp Meetup Organiser Bangalore & Co-Author of Learn Lightweight Kubernetes with k3s (2019) , Packt Publication & also run Non Profit CloudNativeFolks / CloudSecCorner Community To Empower Free Education reach out me twitterhttps://twitter.com/sangamtwts or just follow on GitHub -> https://github.com/sangam14 for Valuable Resources

As you're learning Go, a good quick reference is Go by Example.

For example, here's what it has for for

package main

import "fmt"

func main() {

    i := 1
    for i <= 3 {
        fmt.Println(i)
        i = i + 1
    }

    for j := 7; j <= 9; j++ {
        fmt.Println(j)
    }

    for n := 0; n <= 5; n++ {
        if n%2 == 0 {
            continue
        }
        fmt.Println(n)
    }
}

Note: There is no while in Go.

The way to create a loop is to start with for, and the first thing you put in is an init statement, a condition, and a post, e.g.

  for init; condition; post {
  }

Let's try a loop with an init statment initializing a variable i with the value 0, the condition that i is less than or equal to 100, and the post of incrementing i by 1 (i++). Remember, we can always check the Go spec. In this case, IncDec statements has information explaining the ++ and -- operators.

package main

import (
    "fmt"
)

func main() {
    // for init; condition; post {}
    for i := 0; i <= 100; i++ {
        fmt.Println(i)
    }
}

playground

39 views

GopherLabs

Part 1 of 50

Ultimate Series of Blogs for All Golang Developer

More from this blog

C

CloudNativeFolks Community

140 posts

CloudNativeFolks is non profit community that empower and educate about cloud native technology !