试图了解围棋的心态.我编写了以下函数,查找文件名中包含日期的文件夹的*.txt文件,获取最新日期并返回该日期.
func getLatestDate(path string) (time.Time, error) {
if fns, e := filepath.Glob(filepath.Join(path, "*.txt")); e == nil {
re, _ := regexp.Compile(`_([0-9]{8}).txt$`)
max := ""
for _, fn := range fns {
if ms := re.FindStringSubmatch(fn); ms != nil {
if ms[1] > max {
max = ms[1]
}
}
}
date, _ := time.Parse("20060102", max)
return date, nil
} else {
return time.Time{}, e
}
}
Run Code Online (Sandbox Code Playgroud)
如果有这个函数,这个函数的惯用版本会是什么?
Nic*_*ood 11
这是我的看法
MustCompile编译静态正则表达式.如果它不编译并保存错误检查,这将会引起恐慌return time.Parse 直接检查错误(你之前没有)代码
var dateRe = regexp.MustCompile(`_([0-9]{8}).txt$`)
func getLatestDate(path string) (date time.Time, err error) {
fns, err := filepath.Glob(filepath.Join(path, "*.txt"))
if err != nil {
return
}
max := ""
for _, fn := range fns {
if ms := dateRe.FindStringSubmatch(fn); ms != nil {
if ms[1] > max {
max = ms[1]
}
}
}
return time.Parse("20060102", max)
}
Run Code Online (Sandbox Code Playgroud)