Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

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

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading