tour icon indicating copy to clipboard operation
tour copied to clipboard

tour: Possibly unnecessary addition?

Open igoradamenko opened this issue 5 years ago • 4 comments

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.")
	}
}

igoradamenko avatar Jul 26 '20 21:07 igoradamenko

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

EvanPeterson1324 avatar Jul 29 '20 13:07 EvanPeterson1324

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.

ALTree avatar Aug 23 '20 08:08 ALTree

Thanks! I've created #1034.

igoradamenko avatar Aug 30 '20 18:08 igoradamenko

Looks like this issue is still present in the current go tour.
https://go-review.googlesource.com/c/tour/+/250057?tab=comments

varshapm avatar Jan 14 '25 02:01 varshapm