这个功能的"惯用"版本是什么?

Ana*_*Ana 2 go

试图了解围棋的心态.我编写了以下函数,查找文件名中包含日期的文件夹的*.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

这是我的看法

  1. 使用MustCompile编译静态正则表达式.如果它不编译并保存错误检查,这将会引起恐慌
  2. 提升器将regexp编译出函数 - 你只需要编译一次.请注意,我使用小写的首字母调用它,因此它不会在包外显示.
  3. 在检查错误时使用早期返回 - 这可以节省缩进并且是惯用的
  4. 对那些早期返回使用命名的返回参数 - 保存为类型定义nil值和一般键入(虽然不是每个人的口味)
  5. 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)