Control Structures
if, else if, else
// AND, OR, NOT
if (a == 1 && b == 1) || a == 2 || !b {}
if a {}
else {}
if a == 1 {}
else if a == 2
else {}
switch
If using switch
inside infinite loops, the break
keyword will not be able to be used to end the loop, since it will be used by the switch
.
switch choice {
case 1:
...
break
case 2:
...
default:
...
}
for-loops
Regular
for i := 0; i < 2; i++ {}
Infinite loops
Will run until you break
.
May not break if a switch
is inside. switch
for {
// Until
break
}
Bounded to a variable's value
Will run until boolVariable
is false
.
for boolVariable {}
Looping arrays
index
and value
are arbitrary names.
a := []int{1, 2, 3, 4}
// To get "index" and "value"
for index, value := range a {}
// To discard "index"
for _, value := range a {}
// To discard both "index" and "value"
for range a {}
Looping maps
key
and value
are arbitrary names.
m := map[string]int{
"google": 1,
"aws": 2,
}
// To get "key" and "value"
for key, value := range m {}
// To discard "key"
for _, value := range m {}
// To discard both "key" and "value"
for range m {}
Last updated