Problem:
Converting a string representing a day of the week into an equivalent time.Weekday value presents a challenge. The time package does not include any built-in functionality for this conversion.
Initial Solution:
An initial approach is to utilize an array to store the mapping between day of week strings and their corresponding time.Weekday values. For instance:
<code class="go">var daysOfWeek = [...]string{ "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", } func parseWeekday(v string) (time.Weekday, error) { for i := range daysOfWeek { if daysOfWeek[i] == v { return time.Weekday(i), nil } } return time.Sunday, fmt.Errorf("invalid weekday '%s'", v) }</code>
Recommended Optimization:
To enhance the efficiency and clarity of this conversion, a map is recommended instead of an array. Maps allow for faster lookups, resulting in improved performance.
<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>
Tip:
For a robust solution, a for loop can be employed to safely initialize the daysOfWeek map.
<code class="go">var daysOfWeek = map[string]time.Weekday{} func init() { for d := time.Sunday; d <= time.Saturday; d++ { daysOfWeek[d.String()] = d } }</code>
Additional Parsing Flexibility:
The map-based solution offers an advantage over the array-based approach. By adding additional key-value pairs to the map, additional valid values can be parsed without modifying the parsing logic.
For instance, to parse both the full and 3-letter short names of weekdays, the map can be extended as follows:
<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 extended solution allows for parsing strings like "Mon" or "Fri" into their corresponding time.Weekday values.
The above is the detailed content of How to Convert a String Representation of a Day of Week into a `time.Weekday` Value?. For more information, please follow other related articles on the PHP Chinese website!