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
}
Invest now in Acorns!!! 🚀
Join Acorns and get your $5 bonus!
Acorns is a micro-investing app that automatically invests your "spare change" from daily purchases into diversified, expert-built portfolios of ETFs. It is designed for beginners, allowing you to start investing with as little as $5. The service automates saving and investing. Disclosure: I may receive a referral bonus.
Invest now!!! Get Free equity stock (US, UK only)!
Use Robinhood app to invest in stocks. It is safe and secure. Use the Referral link to claim your free stock when you sign up!.
The Robinhood app makes it easy to trade stocks, crypto and more.
Webull! Receive free stock by signing up using the link: Webull signup.
More Related questions...
