问题:
转换表示一天的字符串工作日价值提出了挑战。时间包不包含任何用于此转换的内置功能。
初始解决方案:
初始方法是利用数组来存储日期之间的映射周字符串及其对应的 time.Weekday 值。例如:<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>
推荐优化:
为了提高转换的效率和清晰度,建议使用映射而不是数组。地图可以实现更快的查找,从而提高性能。<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>
提示:
为了获得可靠的解决方案,可以使用 for 循环来安全地初始化 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>
额外的解析灵活性:
基于地图的解决方案比基于数组的方法具有优势。通过向映射添加额外的键值对,可以在不修改解析逻辑的情况下解析额外的有效值。例如,要解析工作日的完整名称和 3 个字母的短名称,映射可以是扩展如下:<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>此扩展解决方案允许将“Mon”或“Fri”等字符串解析为其相应的时间。工作日值。
以上是如何将星期几的字符串表示形式转换为'time.Weekday”值?的详细内容。更多信息请关注PHP中文网其他相关文章!