I have the following code and ask my self is this the "go way" to solve the following requirement.
I need to print a directory tree sorted by file age.
package main
import (
"fmt"
"github.com/kr/fs"
"os"
"time"
"sort"
)
type fileinfo struct {
Path string
age time.Duration
}
func main() {
fmt.Print("test range of fs")
walker := fs.Walk("../")
var files []fileinfo
for walker.Step() {
if err := walker.Err(); err != nil {
fmt.Fprintln(os.Stderr, err)
continue
}
age := time.Now().Sub(walker.Stat().ModTime())
files = append(files,fileinfo{walker.Path(),age})
}
sort.Slice(files, func(i, j int) bool {
return files[i].age < files[j].age
})
for i:=0; i < len(files) ; i++ {
fmt.Print("File path: ",files[i].Path," age: ",files[i].age,"
")
}
}
What's your opinion to the code?
Thanks for help
for i:=0; i < len(files) ; i++ {
fmt.Print("File path: ",files[i].Path," age: ",files[i].age,"
")
}
for
loops over arrays are better written using range
iterator. This makes the code easier to read, avoids silly mistakes, and it works with other structures like maps and channels.
for _,file := range files {
fmt.Print("File path: ",file.Path," age: ",file.age,"
")
}
See Go by Example: Range for more.
Since you have a newline at the end and a space between each element, fmt.Println
might work out better than fmt.Print
. It automatically puts spaces between each element and a newline at the end.
fmt.Println("File path:", file.Path, "age:", file.age)