0

I am just starting Go and tried implementing switch statement. As far as I know this statement in other languages require "break;" but not in Go. Somehow my code jumps directly into default block. By the time I am writing this question, it is 23/04/2022, Saturday.

P.S. I would be grateful if any of you could suggest me any platforms, where I can take Go courses for free.

This is my code:

package main import ( "fmt" "time" ) func main() { fmt.Println("when is Sunday?") today := time.Now().Weekday() switch time.Sunday { case today + 0: fmt.Println("Today.") case today + 1: fmt.Println("Tommorow.") case today + 2: fmt.Println("In 2 days.") default: fmt.Println("Too far away.") } } 
0

1 Answer 1

2

time.Sunday is a const with the value 0. In your switch you add 1 or 2 to today but the value doesn't loop back around to zero after it reaches a value of 6 (Satureday).

So the second and third clause of your switch will never be true.

This does what you want:

package main import ( "fmt" "time" ) func main() { fmt.Println("when is Sunday?") today := time.Now().Weekday() switch today { case time.Sunday: fmt.Println("Today.") case time.Saturday: fmt.Println("Tommorow.") case time.Friday: fmt.Println("In 2 days.") default: fmt.Println("Too far away.") } } 
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.