CodeGym /コース /Go SELF /Traversal results filtering and sorting

Traversal results filtering and sorting

Go SELF
レベル 41, レッスン 3
使用可能

1. Why filtering is needed

When you first run WalkDir, you want to do this: “find a path — fmt.Println(path)”. That is a normal stage: your brain needs proof that the magic works, not that you accidentally printed your favorite developer mantra: “it works on my machine”.

But as soon as traversal starts producing dozens, hundreds, or thousands of paths, it becomes clear: the output turns into a mess. In real code, you almost never need “everything at once”. Usually you need “only files”, “only .go”, “everything except hidden directories”, “everything that looks like a log”, “everything that starts with task_”. That is where filtering appears: we turn a stream of “everything” into a list of “what we actually need”.

To make it easier to keep this in mind, it helps to think like this:

flowchart LR
    A[WalkDir/ReadDir] --> B["Collecting results into []Item"]
    B --> C[Filtering]
    C --> D[Sorting]
    D --> E[Output / further logic]

We already know how to do stages A and B. Today we will finish C and D.

2. Data model and collecting results

You can filter and sort strings directly “on the fly” inside the callback, but for beginners this often ends with three tasks mixed together in one place: traversal, selection conditions, and output formatting. The code quickly starts to look like earphones pulled from a pocket: useful in principle, but painful to untangle.

So a good practical step is to introduce a result structure that we will collect first and process only after that, in a clean and linear way. Let our study app for today be a small utility called fspeek: it walks a directory, collects the found elements, filters them, and prints them in a predictable order.

Mini data model

Let’s start with a simple type:


package main

import "time"

type Item struct {
	Path    string
	Name    string
	IsDir   bool
	Size    int64
	ModTime time.Time
}

This has everything usually needed for filtering and sorting: path (useful for output), name (useful for rules with HasPrefix/HasSuffix), a directory flag, and a bit of metadata for sorting “by size” and “by modification time”.

Notice a small but important idea: the Size and ModTime fields are metadata. We do not read file contents. We do not open the file for text. We simply look at its “passport”.

Collecting results

Our goal now is not to study WalkDir again, but to get a []Item we can work with. So I will show a minimal “collector” (it will be the basis for the examples below).

package main

import (
	"os"
	"path/filepath"
)

func collect(root string) ([]Item, error) {
	var items []Item

	err := filepath.WalkDir(root, func(path string, d os.DirEntry, err error) error {
		if err != nil {
			return err
		}

		info, err := d.Info()
		if err != nil {
			return err
		}

		items = append(items, Item{
			Path:    path,
			Name:    d.Name(),
			IsDir:   d.IsDir(),
			Size:    info.Size(),
			ModTime: info.ModTime(),
		})
		return nil
	})

	return items, err
}

Yes, this uses d.Info(), and it can be “more expensive” than just d.Name()/d.IsDir(). But for a lecture about sorting by size/time, we need these fields.

In a real app, you often do this: first collect a “lightweight list”, and only fetch metadata if the user asks for sorting “by size”. For now, let’s keep it like this so we do not create too many branches.

3. String filters: HasPrefix, HasSuffix, Contains

Filtering by file name is one of the most common tasks. Almost always you have rules like “do not show hidden items”, “keep only .go”, “find everything similar to a config”.

For this, Go has the strings package, which is pleasantly simple: it does not force you to first earn a degree in regular expressions and go through an initiation rite into “regex wizard”.

Let’s import strings and make a few small predicate functions. A predicate is a function that answers the question “yes/no” (bool). In our case — “keep this item or discard it?”.

Hidden files and directories: HasPrefix(name, ".")

A very typical filter: hidden items in Unix-like systems often start with a dot: .git, .idea, .DS_Store. If you are making a project report, this is almost always noise.

package main

import "strings"

func isHidden(name string) bool {
	return strings.HasPrefix(name, ".")
}

Usage looks like this: if isHidden(it.Name) — we either skip it or, on the contrary, select “only hidden” (yes, sometimes that is useful when you are looking for where .env went).

Files by extension: HasSuffix(name, ".go")

An extension is the second most popular filter. For a study project, it is natural to show “only Go sources”.

package main

import "strings"

func hasExt(name, ext string) bool {
	return strings.HasSuffix(name, ext)
}

For example, hasExt(it.Name, ".go") will keep Go files. hasExt(it.Name, ".md") — markdown.

Substring search: Contains

Sometimes the rule sounds like this: “show everything where the name contains test” or “find everything similar to a log: log”.

package main

import "strings"

func nameContains(name, part string) bool {
	return strings.Contains(name, part)
}

Here it is important to remember that Contains is case-sensitive. That means "Readme.md" does not contain "readme". For “human” search, you often normalize with strings.ToLower.

package main

import "strings"

func nameContainsFold(name, part string) bool {
	return strings.Contains(strings.ToLower(name), strings.ToLower(part))
}

4. Filtering as a separate step: the Filter function and composing conditions

Now we know how to check conditions. But we need a machine that takes []Item and keeps only the needed elements. This is where a good Go style often appears: “a simple function, a simple responsibility, a clear name”.

Basic Filter function

package main

func Filter(items []Item, keep func(Item) bool) []Item {
	var out []Item
	for _, it := range items {
		if keep(it) {
			out = append(out, it)
		}
	}
	return out
}

This function does one thing: it builds a new slice. It does not print, does not sort, does not touch the file system. And that is great: such a function is easy to read, test, and reuse.

Example: keep only files

package main

func onlyFiles(items []Item) []Item {
	return Filter(items, func(it Item) bool {
		return !it.IsDir
	})
}

If somewhere in your heart you love one-liners, yes, you can write it shorter. But now we are learning to write code that a person can read after three cups of coffee and one accidental meeting.

Example: remove hidden elements

package main

func withoutHidden(items []Item) []Item {
	return Filter(items, func(it Item) bool {
		return !isHidden(it.Name)
	})
}

Several conditions at once: a “pipeline” or one pass

Very quickly a request appears: “keep only files” and “only .go” and “not hidden”. Beginners are tempted to write one giant if blanket and then add printing there, and then sorting there too… and that is how you end up in a swamp.

It is much nicer to think about filtering as a pipeline:

package main

func filterGoFiles(items []Item) []Item {
	items = onlyFiles(items)
	items = withoutHidden(items)
	items = Filter(items, func(it Item) bool {
		return hasExt(it.Name, ".go")
	})
	return items
}

Yes, this is several passes over the slice. But for an educational level and most real projects (where we talk about thousands of files, not millions) this is usually fine and much more readable. And if one day it becomes “heavy”, at least you will know exactly which part to optimize, instead of rewriting the whole mess.

Sometimes you still want one pass. That is possible too, the condition just becomes more complex:

package main

func filterGoFilesOnePass(items []Item) []Item {
	return Filter(items, func(it Item) bool {
		return !it.IsDir && !isHidden(it.Name) && hasExt(it.Name, ".go")
	})
}

Both approaches are correct. The first usually wins on readability, the second on minimal work. In a study project we will prefer readability.

5. Sorting: making output deterministic

After filtering, we will have a list that we want to show to the user. And here an unexpected truth appears: “natural order” is a slippery concept. Even if it seems that WalkDir always behaves the same way, it is better not to make that a contract.

Deterministic output matters for comparing results, reproducibility, future tests, and for making sure two runs of the program do not look like a “file randomizer”. So the typical step before output is sorting.

Sorting by path

The most understandable sorting criterion is by path:

package main

import "sort"

func sortByPath(items []Item) {
	sort.Slice(items, func(i, j int) bool {
		return items[i].Path < items[j].Path
	})
}

Note: sorting changes the order in place, directly inside items. So the function returns nothing.

Sorting by size and modification time

Sorting by path is useful almost always, but sometimes you want to see the “top largest files” or the “newest changes”. Here we use the Size and ModTime fields.

By size (descending), biggest first:

package main

import "sort"

func sortBySizeDesc(items []Item) {
	sort.Slice(items, func(i, j int) bool {
		return items[i].Size > items[j].Size
	})
}

By modification time (newest first):

package main

import "sort"

func sortByModTimeDesc(items []Item) {
	sort.Slice(items, func(i, j int) bool {
		return items[i].ModTime.After(items[j].ModTime)
	})
}

After reads almost like English: “i after j” means “i later than j”.

Tie-breaker: when keys are equal

An important nuance: what if two elements have the same size? Or the same time? Then your comparator (less) returns false both for “i less than j” and for “j less than i” (because neither is “less”). In that situation, the order of the “equal” elements can be anything.

If you need a predictable order, add a second criterion — for example, path. This is called a tie-breaker.

package main

import "sort"

func sortBySizeDescThenPath(items []Item) {
	sort.Slice(items, func(i, j int) bool {
		if items[i].Size == items[j].Size {
			return items[i].Path < items[j].Path
		}
		return items[i].Size > items[j].Size
	})
}

Now even if sizes are equal, the order will be stable: by path.

Stable sorting: sort.SliceStable

Sometimes you sort in two passes. For example, you want: first by path, and within identical directories — by size. Or first by size, and equal elements should stay “as they were”. Then you may need stable sorting.

Stable sorting guarantees that elements that are “equal” by the key preserve their relative order from the original array.

package main

import "sort"

func sortStableByName(items []Item) {
	sort.SliceStable(items, func(i, j int) bool {
		return items[i].Name < items[j].Name
	})
}

In everyday practice, it is often easier to use an explicit tie-breaker (as in the example above) than to rely on “preserving the original order”. But it is useful to know that SliceStable exists.

6. Mini program fspeek: filter + sort + print

Now let’s make a short main that ties everything together. It will walk the current directory, keep only .go files (not hidden), sort by path, and print a few fields.

package main

import (
	"fmt"
)

func main() {
	items, err := collect(".")
	if err != nil {
		fmt.Println("collect:", err)
		return
	}

	items = filterGoFiles(items)
	sortByPath(items)

	for _, it := range items {
		fmt.Printf("%s size=%d\n", it.Path, it.Size)
		// ./main.go size=1234
	}
}

Here the important thing is that the code reads like a story:

we collected → filtered → sorted → printed.

If you come back to this code in a week, it will not look like “a magical ritual of three nested loops and two continue statements in a row”.

7. Cheat sheet: which string filter to use when

Sometimes it is useful to have a small cheat sheet. In Go, the strings package is your first Swiss army knife for file names.

Filtering task Function Rule example
Hidden elements
strings.HasPrefix
name starts with "."
Extension
strings.HasSuffix
name ends with ".go"
Substring
strings.Contains
name contains "test"
Case-insensitive search
strings.ToLower + strings.Contains
convert both strings to lower-case

8. Common mistakes

Mistake #1: filtering by path when you actually need to filter by name.
path may contain "./internal/.cache/file.tmp", and if you check HasPrefix(path, "."), you will find almost nothing: a path usually starts with "." only in relative form like "./...", and that is not the same as a “hidden file”. For rules like “a dot at the beginning of the name”, use it.Name (or d.Name() during traversal).

Mistake #2: making one “super-function” that traverses, filters, sorts, and prints at the same time.
Such code first seems fast, and then becomes subtly scary: any change breaks everything. It is much easier to live by the scheme: collect []Item, then filter in a separate stage, then sort, then print. Even if that means several passes over the data, readability pays off.

Mistake #3: forgetting about a tie-breaker and being surprised by a “floating” order.
If you sort only by size, two files of the same size may swap places between runs. This is especially noticeable when you make a report and try to compare the results by eye. Add a second criterion (usually path) or use sort.SliceStable if stability matters.

Mistake #4: expecting sorting to guarantee the order of “equal” elements.
Plain sort.Slice does not have to preserve the order of elements that are considered equal by the key. Moreover, even with the same input, different Go versions or different sort implementations may produce a different order for equal elements. If reproducible output matters, make explicit comparison rules.

Mistake #5: accidentally including directories in the file list and then interpreting Size strangely.
The size of a directory (Size in FileInfo) is not the “total size of all files inside”. If you sort by size and do not filter directories out, folders with “unexpected” numbers may end up at the top — numbers that do not make sense to a person. Usually, before sorting “by file size”, you call onlyFiles(items).

1
タスク
Go SELF, レベル 41, レッスン 3
ロック未解除
ソースナビゲーター
ソースナビゲーター
1
タスク
Go SELF, レベル 41, レッスン 3
ロック未解除
クリーンなディレクトリ
クリーンなディレクトリ
1
タスク
Go SELF, レベル 41, レッスン 3
ロック未解除
大きなファイル
大きなファイル
1
タスク
Go SELF, レベル 41, レッスン 3
ロック未解除
スマート検索
スマート検索
コメント
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION