Convert Day of Week String to time.Weekday
In Go, the time package doesn't offer a built-in function to convert a string representing a day of the week into a time.Weekday value. So, a common solution is to create a custom function to perform this conversion.
One approach is to use an array to store the weekday names and their corresponding time.Weekday values. However, a more efficient and idiomatic solution is to utilize a map.
Using a Map for Conversion:
A map provides faster and direct lookups compared to an array. Here's a snippet demonstrating this approach:
<code class="go">var daysOfWeek = map[string]time.Weekday{ "Sunday": time.Sunday, "Monday": time.Monday, // ... and so on for all weekdays } 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>
Safely Initializing the Map:
To ensure correct initialization, you can use a for loop to populate 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>
Extending the Conversion:
The map-based solution allows for easy extension. For instance, you can add 3-letter short weekday names as valid input:
<code class="go">func init() { // ... existing initialization code for d := time.Sunday; d <= time.Saturday; d++ { name := d.String() daysOfWeek[name] = d daysOfWeek[name[:3]] = d } }</code>
Conclusion:
Using a map for weekday string conversion in Go is both efficient and flexible. It allows for easy lookups, safe initialization, and straightforward extension to accommodate alternative input formats.
The above is the detailed content of How to Convert a Day of Week String to `time.Weekday` in Go?. For more information, please follow other related articles on the PHP Chinese website!