March 2019
Beginner to intermediate
324 pages
7h 17m
English
Now, let's look at the switch statement. Here is what it looks like:
switch x { case 5: fmt.Println("5") case 6: fmt.Println("6")default: fmt.Println("default case")}
If you haven't noticed already, there is no break keyword. In Go, each case breaks automatically, and doesn't need to be told to do so.
Similar to if statements, you can do an initialization in your switch statement:
switch x := getX();x { case 5: fmt.Println("5") case 6: fmt.Println("6")default: fmt.Println("default case")}
In Go, a switch statement can act like a group of if else. This gives you the ability to write long if else chains with much nicer code:
switch{case x == 5://do somethingcase x > 10:// do something elsedefault://default case}
In some ...
Read now
Unlock full access