If...Else if...Else

If…Else…

The syntax of Golang is very similar to Python, parentheses are not needed here for condition:

1
2
3
4
5
6
7
8
9
func bounded(v int) int {
if v > 100 {
return 100
} else if v < 0 {
return 0
} else {
return v
}
}

Let’s do something more complex than just setting the number boundaries. Let’s use if...else... to test some io file reading features.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
package main

import (
"fmt"
"io/ioutil"
)

func main() {
const filename = "abc.txt"
contents, err := ioutil.ReadFile(filename)

if err != nil {
fmt.Println(err)
} else {
fmt.Printf("%s\n", contents)
}
}

Since I haven’t created abc.txt yet, the code above will generate an error

1
open abc.txt: The system cannot find the file specified.

Now I will add the abc.txt, by the way, the contents are famous Zen of Python.

Once the file is added, the above will print out the Zen of Python (Will there be a Zen of Go)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
The Zen of Python, by Tim Peters

Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren't special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one-- and preferably only one --obvious way to do it.
Although that way may not be obvious at first unless you're Dutch.
Now is better than never.
Although never is often better than *right* now.
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea -- let's do more of those!

Shorter Format

Here is a syntax candy in Go, the above if...else... can be refactored as such:

1
2
3
4
5
6
7
8
func main() {
const filename = "abc.txt"
if contents, err := ioutil.ReadFile(filename); err != nil {
fmt.Println(err)
} else {
fmt.Printf("%s\n", contents)
}
}

But the downside is contents and err are defined in the if...else block, they can’t be accessed outside this block.

To sum up, we can define variables and assign values in the condition. The scope of vars defined in the condition is within the if block only.

Switch

Unlike Python, Go has switch and the syntax is simpler than that in C/C++

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
func eval(a, b int, op string) int {
var result int
switch op {
case "+":
result = a + b
case "-":
result = a - b
case "*":
result = a * b
case "/":
result = a / b
case "%":
result = a % b
default:
panic("unsupported operator: " + op)
}
return result
}

func main() {
fmt.Println(eval(30, 20, "%"))
}

For switch in Go, each case has break by default, to disable this behavior, use fallthrough

Support range condition check

Unlike in C/C++, switch is mainly used in == cases, in Go, switch can be used to check a range, e.g. < or >=

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
func grade(score int) string {
res := ""
switch {
case score < 0 || score > 100:
panic(fmt.Sprintf("Wrong score:%d", score))

case score < 60:
res = "Failed"

case score < 80:
res = "C"

case score < 90:
res = "B"

case score <= 100:
res = "A"
}
return res
}

The expression is not needed after switch and it can be moved after case for condition check.