Golang blocks — if, for, switch and defer
To be honest I was not sure if I would write an article about these “blocks” because they are doing literally the same thing in “all” programming languages. But because they have a different syntax and some other nice sugar (and I will have a nice cheat sheet for at least myself) I have decided to write one 🙂.
I hope I don’t have to explain what if
, for
and switch
do. So I will just put some code in here without that much explanation. But I will explain the defer
thing a little bit more in detail. This is not very common in other languages and needs a bit more attention.
if — else if — else
The default syntax looks like the following:
if x == 3 {
// Code
} else if x == 2 {
// Code
} else {
// Code
}
The difference to some other languages here is that the statements don’t have to be surrounded by parentheses. Only the curly brackets are required.
A nice feature which is also new is that you can add a short statement before the actual statement:
if x := calculate(); x == 0 {
fmt.Println("X is zero!")
} else {
fmt.Println("X is", x)
}
The declared variable in that statement is only available inside the if/elseif/else
block. Afterwards it isn’t accessible anymore and leads to an undefined
compiler error.
for
loops
Golang loops are always for
loops. Other languages have sometimes also while
or do-while
loops. These keywords don’t exist in go — but the same loops can be created with it. To “manipulate” a loop break
and continue
are also available:
// "Default" loop
for i := 1; i < 10; i++ {
fmt.Println(i)
}// "While" loop
for i < 10 {
i += 1
if i % 2 == 0 {
continue
} else {
fmt.Println(i)
}
}
// "Infinite" loop which break directly
for {
break
}
switch — case — default
The switch
statement has also different “flavors”. It can be created without a statement, with a statement and with a short statement before the actual statement… 🤯:
// Switch without a statement
switch {
case number == 0:
fmt.Println("Number is zero")
case number == 1:
fmt.Println("Number is one")
default:
fmt.Println("I don't know what number is...")
}// Switch with a statement
switch number {
case 0:
fmt.Println("Number is zero")
case 1:
fmt.Println("Number is one")
default:
fmt.Println("I don't know what number is...")
}// Switch with a short statement
switch number := 0; number {
case 0:
fmt.Println("Number is zero")
case 1:
fmt.Println("Number is one")
default:
fmt.Println("I don't know what number is...")
}
break
in the cases
is not available because Golang will only execute the case
which will satisfy the condition. When two cases
are met the condition the first one will be picked.
The statement for the switch
doesn’t have to be a number. It could also be a string
or some other type.
To defer something
To be honest I’ve never seen a concept like the defer
in Golang in other programming languages. And at time of writing I’m not sure in which situations I would use it. But maybe my first real program will tell me…
Anyway. You can add defer
before a function call and it will be— please don’t get confused now — evaluated immediately but executed when the “containing function” returns.
What does it mean in practice? Well, you can call a func
but it will be executed later! But what you call “inside” this defer
will be evaluated immediately. For example variables which you put into the function will have the value while you call the function. Not the one which will have it when the “containing function” returns:
func main() {
doSomething()
}func doSomething() {
aBoolValue := true
defer executeLaterWhenTrue(aBoolValue)
aBoolValue = false
}func executeLaterWhenTrue(boolean bool) {
if boolean {
fmt.Println("I was executed")
}
}
The output from this program will be I was executed
. But when you switch the aBoolValue
assignments (set it first to false
and then to true
) it will print nothing.
This is because the function executeLaterWhenTrue
is called after doSomething
returns but the aBoolValue
will be evaluated “in time”, not when doSomething
returns.
Learning sources
I’ve learned this from A Tour of Go.