Golang / GoLang Concurrency Mastery Interview Questions
Implement a concurrent word count across multiple files — a classic Go interview puzzle.
This exercise tests goroutine spawning, WaitGroup usage, channel fan-in, and safe result aggregation. It is a common live-coding assignment in Go technical screens.
package main import ( "bufio" "context" "fmt" "os" "sync" ) type FileCount struct { File string Words int Err error } func countWords(ctx context.Context, path string) FileCount { f, err := os.Open(path) if err != nil { return FileCount{File: path, Err: err} } defer f.Close() scanner := bufio.NewScanner(f) scanner.Split(bufio.ScanWords) count := 0 for scanner.Scan() { select { case <-ctx.Done(): return FileCount{File: path, Err: ctx.Err()} default: } count++ } return FileCount{File: path, Words: count, Err: scanner.Err()} } func parallelWordCount(ctx context.Context, files []string) (int, []error) { results := make(chan FileCount, len(files)) // buffered â no goroutine blocks var wg sync.WaitGroup for _, f := range files { wg.Add(1) go func(path string) { defer wg.Done() results <- countWords(ctx, path) }(f) } go func() { wg.Wait(); close(results) }() total := 0 var errs []error for r := range results { if r.Err != nil { errs = append(errs, fmt.Errorf("%s: %w", r.File, r.Err)) continue } total += r.Words } return total, errs }
More Related questions...