Graph DFS Topological Sort (Go)
Perform topological sort on a Go DAG using DFS with cycle detection via tri-color marking.
Code
package main
import "errors"
func topologicalSort(graph map[string][]string) ([]string, error) {
color := map[string]int{}
var result []string
var dfs func(node string) error
dfs = func(node string) error {
if color[node] == 1 { return errors.New("cycle at " + node) }
if color[node] == 2 { return nil }
color[node] = 1
for _, neighbor := range graph[node] { if err := dfs(neighbor); err != nil { return err } }
color[node] = 2
result = append(result, node)
return nil
}
for n := range graph { if color[n] == 0 { if err := dfs(n); err != nil { return nil, err } } }
for i, j := 0, len(result)-1; i < j; i, j = i+1, j-1 { result[i], result[j] = result[j], result[i] }
return result, nil
}How it works
Count the function topologicalSort as the entire surface area of Graph DFS Topological Sort (Go).
for _, neighbor := range graph[node] { if err := dfs(neighbor); err != nil { return err } } is the loop that carries the per-item work. Every fallible call checks err != nil (2 sites), so an error is handled where it happens rather than bubbling invisibly.
Points of care
erroris part of the return tuple, so every caller decides what failure means.
Applying it
Entry signature: func topologicalSort(graph map[string][]string) ([]string, error)
Statements that matter
for n := range graph { if color[n] == 0 { if err := dfs(n); err != nil { return nil, err } } }
for _, neighbor := range graph[node] { if err := dfs(neighbor); err != nil { return err } }
if color[node] == 1 { return errors.New("cycle at " + node) }
Interactive Tools for This Topic
cURL to Python & Go ConverterTranslate curl CLI commands with headers, auth, JSON bodies, and timeouts into ready-to-run Python requests and Go net/http client code snippets.Line SorterSort text lines ascending or descending with numeric-aware ordering, duplicate removal, empty-line filtering, and locale-aware comparison.SRI Hash GeneratorGenerate Subresource Integrity (SRI) hashes from resource content using SHA-256, SHA-384, or SHA-512, and copy a ready-to-use script tag.
FAQ
- What happens when a call fails?
- As returned `error` values, checked at 2 sites — callers must branch on `err` before using the other return values. No panics or exceptions in the snippet.
- What does the package manager see?
- An empty dependency file. The snippet imports nothing that needs fetching. The file defines `topologicalSort` at load time.
Report a problem with this exampleOpens a pre-filled issue on GitHub.