试着理解围棋的心态。我编写了以下函数来查找文件名中包含日期的文件夹的*.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
}
}如果有的话,这个函数的更常用的版本是什么?
发布于 2013-11-17 16:20:38
以下是我的观点
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)
}发布于 2013-11-17 16:24:23
下面是我会怎么写的。不要忽略错误,使用保护子句进行错误处理,并且不要在循环中重新编译regexp。
var datePat = regexp.MustCompile(`_([0-9]{8}).txt$`)
func getLatestDate(path string) (time.Time, error) {
fns, err := filepath.Glob(filepath.Join(path, "*.txt"))
if err != nil {
return time.Time{}, err
}
max := time.Time{}
for _, fn := range fns {
if ms := re.FindStringSubmatch(fn); ms != nil {
if t, err := time.Parse("20060102", ms[1]); err == nil && t.After(max) {
max = t
}
}
}
return max, nil
}https://stackoverflow.com/questions/20028579
复制相似问题