According to the Go Specification, break and continue are keywords.
break default func interface select
case defer go map struct
chan else goto package switch
const fallthrough if range type
continue for import return var
break will break out of a loop. It's a way to stop looping.
continue will move on to the next iteration. Let's see it in action.
Aside dividing and remainders
package main
import (
"fmt"
)
func main() {
x := 83 / 40
y := 83 % 40
fmt.Println(x, y)
}
note: % (modulo) is an Arithmetic operator that gives the remainder.
Back to continue in action. Let's say we want to iterate from 1 through to 100, and print out only the even numbers, we can use for, if, and continue
package main
import (
"fmt"
)
func main() {
x := 0
for {
x++
// break out of the loop (stop the loop)
// if x is greater than 100
if x > 100 {
break
}
// continue to the next iteration if the
// remainder of x divided by 2 is not 0
// (if x is not even)
if x%2 != 0 {
continue
}
fmt.Println(x)
}
fmt.Println("done.")
}
About the author
- 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
Comments
Join the discussionNo comments yet. Be the first to comment.



