Home > Article > Backend Development > How Do I Convert Weekday Strings to time.Weekday in Go Efficiently?
Parse Weekday String into time.Weekday: An Idiomatic Approach with a Map
Converting a weekday string into a corresponding time.Weekday value in Go requires a custom solution since there's no built-in functionality for this conversion. While the presented array-based function provides a workable solution, a map-based approach offers advantages in efficiency and flexibility.
Enhanced Solution Using a Map
Instead of using an array, utilizing a map with weekday strings as keys and their corresponding time.Weekday values as values significantly speeds up lookups and simplifies the code:
<code class="go">var daysOfWeek = map[string]time.Weekday{ "Sunday": time.Sunday, "Monday": time.Monday, "Tuesday": time.Tuesday, "Wednesday": time.Wednesday, "Thursday": time.Thursday, "Friday": time.Friday, "Saturday": time.Saturday, } func parseWeekday(v string) (time.Weekday, error) { if d, ok := daysOfWeek[v]; ok { return d, nil } return time.Sunday, fmt.Errorf("invalid weekday '%s'", v) }</code>
Benefits of the Map-Based Approach
<code class="go">var daysOfWeek = map[string]time.Weekday{} func init() { for d := time.Sunday; d <= time.Saturday; d++ { daysOfWeek[d.String()] = d } }</code>
Expanding the Map for Additional Input
This map-based approach also allows for the flexible addition of new valid values that can be parsed into time.Weekday. For example, short 3-letter weekday names can be included with a simple loop:
<code class="go">var daysOfWeek = map[string]time.Weekday{} func init() { for d := time.Sunday; d <= time.Saturday; d++ { name := d.String() daysOfWeek[name] = d daysOfWeek[name[:3]] = d } }</code>
This extension allows parsing both full weekday names (e.g., "Monday") and short weekday names (e.g., "Mon") into time.Weekday.
Using a map in this context provides a faster, more convenient, and extendable way to parse weekday strings into time.Weekday values in Go.
The above is the detailed content of How Do I Convert Weekday Strings to time.Weekday in Go Efficiently?. For more information, please follow other related articles on the PHP Chinese website!