Understanding For Loops in Golang

0 min read 128 words

In Golang a for loop is a way to loop through an iterable.

The most basic For Loop

i := 0
for i <= 3 {
  i = i + 1
}

A classic For Loop

for i := 7; i <= 9; i++ {
  // do something
}

For Loop without Conditions

A for without a condition will loop forever, until either a break or return is hit.

for {
  // do something
  break // kill the loop
}

When to use continue

A continue will move to the next iteration of the loop

for i := 0; i <= 5; i++ {
  if i%2 == 0 {
    // skip if even number
    continue // move to next iteration
  }
  // do something with odd number
}
Tags:
Andrew
Andrew

Andrew is a visionary software engineer and DevOps expert with a proven track record of delivering cutting-edge solutions that drive innovation at Ataiva.com. As a leader on numerous high-profile projects, Andrew brings his exceptional technical expertise and collaborative leadership skills to the table, fostering a culture of agility and excellence within the team. With a passion for architecting scalable systems, automating workflows, and empowering teams, Andrew is a sought-after authority in the field of software development and DevOps.

Tags

Recent Posts