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.
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
The result is:
two
You can also put multiple conditions in one case like below:
The result is:
one, five or ten
You can also use initialise in switch statement:
The result is:
one, five or ten
Reference: https://www.youtube.com/watch?v=YS4e4q9oBaU&t=7285s
Comments
Post a Comment