Go ControlFlow Flashcards
How many looping constructs are available in Go?
Only 1 - “For Loop”
What are different variations of For loop ?
- Loop till condition
- Loop till condition with “post clause”
- Loop over collections
- Infinite Loop
Is there any other “println” function apart from “fmt” package ?
Yes, the built-in “println” function.
What’s the main purpose of built-in “println” function ?
Debugging
How to declare “for-till-condition” loop ?
It only requires a “condition” after “for” keyword:
»>
var i int
for i < 5 {
println(i)
i++
}
»>
How to use “break” and “continue” statement with For loop ?
Used with “if-statement”:
»>
for i< 5 {
if i==3 {
continue //or break
}
}
How to declare “for-till-condition-with-post-clause” ?
> > > for i := 0 ; i < 5 ; i++ {
println(i)
}
How many semicolons are mandatory in “for-till-condition-with-post-clause” loop ?
Three
Can we declare the loop variable outside the for loop scope in “for-till-condition-with-post-caluse” loop ?
Yes, but we need to use the semicolon.
»>
var i int
for ; i<5 ; i++ {
println(i)
}
Declare infinite loop in Go-Lang ?
for {
println(“infiinte”)
}
Which keyword is required to iterate through any collection in Go ?
“range” keyword
What is returned by the “range” keyword ?
It returns:
1. index, value - in case of Arrays and slices
2. key, value - in case of Map
How to use for loop to iterate Array and Slices ?
> > > for i,v := range mySlice {
println(i,v)
}
Can we use only one value returned by “range” keyword instead of two ?
Yes, by ignoring the other value using “underscore”.
»>
for _ , v := range mySLice {
println(v)
}
»>
How to use “for loop” to iterate a Map ?
for k , v := range myMap {
println(k,v)
}