Home  >  Article  >  Backend Development  >  How to Convert a Day of Week String to `time.Weekday` in Go?

How to Convert a Day of Week String to `time.Weekday` in Go?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-10-31 04:38:30776browse

How to Convert a Day of Week String to `time.Weekday` in Go?

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn