golang / tour

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

tour: Possibly unnecessary addition? #1003

Open igoradamenko opened 4 years ago

igoradamenko commented 4 years ago

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

Hey there!

I'm probably getting this wrong, but why is the + 0 in this code?

package main

import (
    "fmt"
    "time"
)

func main() {
    fmt.Println("When's Saturday?")
    today := time.Now().Weekday()
    switch time.Saturday {
    case today + 0:                        // <-- this one
        fmt.Println("Today.")
    case today + 1:
        fmt.Println("Tomorrow.")
    case today + 2:
        fmt.Println("In two days.")
    default:
        fmt.Println("Too far away.")
    }
}

I thought it might do some type coercion or so, and otherwise the first case-branch wouldn't match, but when I changed the tested weekday and removed + 0 it worked as expected:

package main

import (
    "fmt"
    "time"
)

func main() {
    fmt.Println("When's Tuesday?")
    today := time.Now().Weekday()
    switch time.Tuesday {
    case today:
        fmt.Println("Today.")          // evaluates this branch
    case today + 1:
        fmt.Println("Tomorrow.")
    case today + 2:
        fmt.Println("In two days.")
    default:
        fmt.Println("Too far away.")
    }
}
EvanPeterson1324 commented 4 years ago

Seems like it was written as such for consistency. I had the same thought that this might not be needed though.

ALTree commented 4 years ago

It was likely done just to preserve alignment or for consistency... but I agree that it just makes the code more confusing. It looks like it's needed, but it's not, really.

igoradamenko commented 4 years ago

Thanks! I've created #1034.