2 回答
TA贡献1780条经验 获得超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"to 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'
TA贡献2065条经验 获得超13个赞
这看起来是这样做的:
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)
}
https://golang.org/pkg/time#Parse
- 2 回答
- 0 关注
- 90 浏览
添加回答
举报