golang / tour

[mirror] A Tour of Go
BSD 3-Clause "New" or "Revised" License
1.54k stars 521 forks source link

switch cases can be constants and the values can be integers #458

Open paperx123 opened 6 years ago

paperx123 commented 6 years ago

Context: https://tour.golang.org/flowcontrol/9

" Another important difference is that Go's switch cases need not be constants, and the values involved need not be integers. "

If I am reading this correctly, it seems not the case now. For example, code works fine as below.

    const myConst = 5
switch rd := rand.Intn(10); rd {
case 1:
    fmt.Println(rd)
case myConst:
    fmt.Println("binggo myConst", rd)
    switch myConst {
    case 0:
        fmt.Println("is 0")
    default:
        fmt.Println("not 0")
    }
default:
    fmt.Println("goodbye", rd)
}
capripot commented 6 years ago

Yeah, I got confused by the statement too as when I tried in the console, it worked fine.

bgadrian commented 6 years ago

Another important difference is that Go's switch cases need not be constants, and the values involved need not be integers.

I think the statement is confusing and wrong, it implies that "need not to be", but in reality can be a constant. Also it says "difference" and then state 2 of them.

I suggest something like:

Another 2 important differences are: Go's switch control expression (switch expresssion {) does not need to be a constant value and the values can be of any type, not restricted to integers.

Although I would remove the 2nd difference, I don't know any mainstream language that has the integer restriction.

ghost commented 6 years ago

As I noticed they are usually comparing things with C. Seems in C in must be constant and integer or convertible to integer. So I think the statement have been misunderstood. It's saying that in Go it don't need to be constant or integer, there is no restriction.

Anyway will be better if someone will confirm my assumption.