Home > OS >  Why does my code jump straight to default? Switch case in Go
Why does my code jump straight to default? Switch case in Go

Time:04-24

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

CodePudding user response:

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