tour: Possibly unnecessary addition?
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.")
}
}
Seems like it was written as such for consistency. I had the same thought that this might not be needed though.
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.
Thanks! I've created #1034.
Looks like this issue is still present in the current go tour.
https://go-review.googlesource.com/c/tour/+/250057?tab=comments