Am I writing good Go here? Python functions converted to Go
I originally asked this question on StackOverflow. Reproduced here by recommendation.
I've got a number of Python scripts that I'm considering converting to Go. I'm seeking confirmation that I'm using Go in essentially the way it was meant to be used. Full code is available here: https://gist.github.com/anonymous/7521526
So the primary question is: Am I writing what is considered "good Go" ?
Python function #1: Look at the files in a folder and extract the latest encoded date in the filenames.
def retrieveLatestDateSuffix(target):
return max(map("".join, filter(lambda x: x,
map(lambda x: re.findall(r"_([0-9]{8})\.txt$", x),
os.listdir(target)))))
My translation for #1:
var rldsPat = regexp.MustCompile(`_([0-9]{8})\.txt$`)
func retrieveLatestDateSuffix(target string) (string, error) {
if fis, e := ioutil.ReadDir(target); e == nil {
t := ""
for _, fi := range fis {
if m := rldsPat.FindStringSubmatch(fi.Name()); m != nil {
if m[1] > t { t = m[1] }
}
}
return t, nil
} else {
return "", e
}
}
Python function #2: Add a date suffix to each filename inside a folder that doesn't already have a suffix added. Printing the from/to for now instead of doing the rename.
def addDateSuffix(target, suffix):
for fn in filter(lambda x: re.search(r"(?<!_[0-9]{8})\.txt$", x), os.listdir(target)):
pref, ext = os.path.splitext(fn)
gn = "{0}_{1}{2}".format(pref, suffix, ext)
print(fn, " -> ", gn)
My translation for #2:
var adsPat1 = regexp.MustCompile(`\.txt$`)
var adsPat2 = regexp.MustCompile(`_[0-9]{8}\.txt$`)
func addDateSuffix(target string, suffix string) error {
if fis, e := ioutil.ReadDir(target); e == nil {
for _, fi := range fis {
if m1 := adsPat1.FindStringSubmatch(fi.Name()); m1 != nil {
if m2 := adsPat2.FindStringSubmatch(fi.Name()); m2 == nil {
ext := filepath.Ext(fi.Name())
gn := fmt.Sprintf("%s_%s%s", strings.TrimSuffix(fi.Name(), ext), suffix, ext)
fmt.Println(fi.Name(), "->", gn)
}
}
}
return nil
} else {
return e
}
}