gpt4 book ai didi

go - 这个函数的 "idiomatic"版本是什么?

转载 作者:IT王子 更新时间:2023-10-29 01:17:11 24 4
gpt4 key购买 nike

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

如果有的话,这个函数的更惯用的版本是什么?

最佳答案

这是我的想法

  1. 使用MustCompile 编译静态正则表达式。如果它不编译并保存错误检查,这将 panic
  2. 从函数中提升编译正则表达式——你只需要编译一次。请注意,我用小写首字母调用它,这样它就不会在包装外可见。
  3. 在检查错误时使用提前返回 - 这样可以节省缩进并且是惯用的 go
  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)
}

关于go - 这个函数的 "idiomatic"版本是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20028579/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com