我遇到了将“星期几”字符串转换为time.Weekday
值的问题。我找不到time
包中内置的任何内容。
然后,我编写了这个简单的函数(满足了我的需求):
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)
}
还有其他推荐或更多惯用方式在Golang中执行此转换吗?
谢谢!
答案 0 :(得分:3)
是的,使用映射而不是数组,因此查找更快,更直接:
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)
}
测试:
fmt.Println(parseWeekday("Monday"))
fmt.Println(parseWeekday("Friday"))
fmt.Println(parseWeekday("invalid"))
输出(在Go Playgorund上尝试):
Monday <nil>
Friday <nil>
Sunday invalid weekday 'invalid'
提示:
您甚至可以使用for
循环来安全地初始化daysOfWeek
映射,如下所示:
var daysOfWeek = map[string]time.Weekday{}
func init() {
for d := time.Sunday; d <= time.Saturday; d++ {
daysOfWeek[d.String()] = d
}
}
测试和输出是相同的。在Go Playground上尝试这个。
此映射解决方案的另一个不错的属性(与数组解决方案相比)是,您可以在同一映射中列出可以解析为time.Weekday
的其他有效值,而无需其他解析代码。
例如,让我们还将3个字母的简短工作日名称解析为与它们相等的time.Weekday
,例如"Mon"
至time.Monday
。
可以通过一个简单的循环添加此扩展名:
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
}
}
测试:
fmt.Println(parseWeekday("Monday"))
fmt.Println(parseWeekday("Friday"))
fmt.Println(parseWeekday("Mon"))
fmt.Println(parseWeekday("Fri"))
fmt.Println(parseWeekday("invalid"))
输出(在Go Playground上尝试):
Monday <nil>
Friday <nil>
Monday <nil>
Friday <nil>
Sunday invalid weekday 'invalid'
答案 1 :(得分:0)
这看起来可以做到:
package main
import "time"
func parseWeekday(v string) (time.Weekday, error) {
t, e := time.Parse("Monday 2", v + " 2")
if e != nil { return 0, e }
return t.Weekday(), nil
}
func main() {
n, e := parseWeekday("Sunday")
if e != nil {
panic(e)
}
println(n == time.Sunday)
}