Python’s elif in Go using switch

Michał Łowicki
golangspec

--

In many cases it’s hard to convince programmer that other language is a viable alternative. It’s especially true when he or she is proficient with particular language and got used to the mechanics there. You need to be well equipped with knowledge and a bit of experience to find answers to many of such arguments but it isn’t always that hard. Complain I hear a lot is lack of elif construct as in Python:

if foo == 0:
print("foo equals 0")
elif foo + bar == 3:
print("foo + bar equals 3")
else:
print("nothing is true..")

which can be used to test many expressions and at the same time avoid excessive indentations using traditional if … else approach like in C:

if (foo == 0) {
printf("foo equals 0\n");
}
else {
if (foo + bar == 3) {
printf("foo + bar equals 3\n");
}
else {
printf("nothing is true....\n");
}
}

In Golang off the shelf we can use syntax which is pretty close to Python’s archetype:

if foo == 0 {
fmt.Printf("foo equals 0")
} else if foo+bar == 3 {
fmt.Printf("foo + bar equals 3")
} else {
fmt.Printf("nothing is true....")
}

but there is even more compact and readable way applicable if number of expressions is long…

switch statement allow to omit expression completely and it’s the same as setting it to true explicitly:

switch {
case foo == 0:
fmt.Printf("foo equals 0")
case foo+bar == 3:
fmt.Printf("foo + bar equals 3")
case foo-bar == 5:
fmt.Printf("foo - bar equals 5")
case bar == 7:
fmt.Printf("bar equals 7")
default:
fmt.Printf("nothing is true...")
}

Resources:

--

--

Michał Łowicki
golangspec

Software engineer at Datadog, previously at Facebook and Opera, never satisfied.