Special handing of conditional statements in Go

This is a study note of YouTube tutorial: https://www.youtube.com/watch?v=YS4e4q9oBaU&t=7285s

Here I will only discuss the special usage of conditional statements in Go compared to other traditional programming languages like Java, C/C++...

Initialiser syntax

Here I give an example directly from the tutorial.

func main() {
statePopulations := map[string]int{
"California": 39250017,
"Texas": 27862596,
"Florida": 20612439,
"Pennsylvania": 12802503,
"Illinois": 12801539,
"Ohio": 11614273,
}
if pop, ok := statePopulations["Florida"]; ok {
fmt.Println(pop)
}
}

The result is:

20612439

There are two parts in above if statement if pop, ok := statePopulations["Florida"]; ok. The first part before the semicolon is the initialiser where you can initialise some variables. The second part after the semicolon is the condition. Be aware that the variables defined in the initialiser part are only alive in the if block. If you try to use the variable ("pop" and "ok") after the if statement, you will get an undefined variable error.

switch statement

Unlike other programming languages where switch statement needs to use "break" to skip the following cases. In Go, by default it only executes the statements in the case block, then exit the switch statement (In fact, in GO you can use "break" as well to exit early where you need it to).

func main() {
switch 2 {
case 1:
fmt.Println("one")
case 2:
fmt.Println("two")
default:
fmt.Println("not one or two")
}
}

The result is:

two

You can also put multiple conditions in one case like below:

func main() {
switch 5 {
case 1, 5, 10:
fmt.Println("one, five or ten")
case 2, 4, 6:
fmt.Println("two, four or fix")
default:
fmt.Println("other number")
}
}

The result is:

one, five or ten

You can also use initialise in switch statement:

func main() {
switch i := 2 + 3; i {
case 1, 5, 10:
fmt.Println("one, five or ten")
case 2, 4, 6:
fmt.Println("two, four or fix")
default:
fmt.Println("other number")
}
}

The result is:

one, five or ten



Reference: https://www.youtube.com/watch?v=YS4e4q9oBaU&t=7285s

Comments

Popular posts from this blog

Basic understanding of TLS-PSK protocol

Differences between ASIC, ASSP and ASIP

Orthogonal instruction set