0

I've slightly modified a very simple Switch example from "A Tour of Go" website:

package main

import (
    "fmt"
    "time"
)

func main() {
    day := "Wednesday"
    fmt.Printf("When's %s?\n", day)
    today := time.Now().Weekday()
    switch time.Wednesday {
    case today + 0:
        fmt.Println("Today.")
    case today + 1:
        fmt.Println("Tomorrow.")
    case today + 2:
        fmt.Println("In two days.")
    default:
        fmt.Println("Too far away.")
    }
}

Instead of time.Wednesday I would like to use the value of day to fetch the time.Weekday.
In Python/JS it would be time[day].
How does one do this in Go ?

Asaf
  • 8,106
  • 19
  • 66
  • 116
  • 4
    In Go you can't do this. So the compiler can make optimizations if something is not referred to explicitly, it can be left out from the final binary. – icza Jun 03 '20 at 16:55
  • 2
    See [one](https://stackoverflow.com/questions/40879748/golang-reflect-get-type-representation-from-name/40882963#40882963); [two](https://stackoverflow.com/questions/38875016/splitting-client-server-code/38875901#38875901); and [three](https://stackoverflow.com/questions/37384473/call-functions-with-special-prefix-suffix/37384665#37384665). – icza Jun 03 '20 at 16:56
  • 2
    I may be terribly misunderstanding the question, but what's wrong with having a map that is initialized on load? Like - `map[string]time.Weekday{"Monday": time.Monday, ...}` – Tarun Khandelwal Jun 03 '20 at 16:59
  • 1
    `time` does not provide a `Parse` function for `Weekday`. – Adrian Jun 03 '20 at 16:59
  • 2
    For parsing a weekday string into a `time.Weekday`, see [Parse Weekday string into time.Weekday](https://stackoverflow.com/questions/52456226/parse-weekday-string-into-time-weekday/52456320#52456320). – icza Jun 03 '20 at 17:11

0 Answers0