On Wed, 19 Oct 2016 06:27:47 -0700 (PDT)
hannover.p...@gmail.com wrote:

> Please, can you explain the follwing output:
> 
> >4
> =5
> <4
> 
> ---
> 
> // Go 1.7.1
> 
> package main
> 
> import "fmt"
> 
> func main() {
>        x := 5
> 
>        switch {
>        case x > 4:
>               fmt.Println(">4")
>               fallthrough
>        case x == 5:
>               fmt.Println("=5")
>               fallthrough
>        case x < 4:
>               fmt.Println("<4")
>        }
> }

In addition to what Ian said, the way to understand how this works,
is to compare it with how it works in C.  In C, where the "classic"
switch was implemented (and then copied to many different languages),
branches of this statement felt through by default -- unless an
explicit "break" statement was terminating a branch.

The idea behind that approach supposedly was to implement a single
"wall of code" with several entry points into it -- the branches.
Once the control flow enters that wall of code, it executes to its end.

Over the years, many programmers (especially novice ones) were bitten
by that feature supposedly because many were perceiving the switch
statement not as that "wall of code with multiple entry points" but
rather like a more convenient way to write multiple-branch if-then-else
statements.

Hence AFAIK Go codified that "new" approach to implementing the switch
statement: the branches don't fall through by default but they can if
you wish to have that explicitly.

Hope this helps.

-- 
You received this message because you are subscribed to the Google Groups 
"golang-nuts" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to golang-nuts+unsubscr...@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Reply via email to