/Go Essentials
🐹
Go Essentials
Day 2 · Backend / Go · 45 min
Goroutines: Lightweight threads managed by Go runtime. Cost ~2KB stack each.
go func() {
// runs concurrently
result := processPayment(tx)
resultChan <- result
}()
Channels: Type-safe communication between goroutines.
ch := make(chan Transaction, 100) // buffered channel
ch <- tx // send
received := <-ch // receive
// Select for multiple channels
select {
case tx := <-txChan:
process(tx)
case <-ctx.Done():
return ctx.Err()
case <-time.After(30 time.Second):
return ErrTimeout
}
Context: Carries deadlines, cancellation, and request-scoped values.
func ProcessSettlement(ctx context.Context, tx Transaction) error {
ctx, cancel := context.WithTimeout(ctx, 30time.Second)
defer cancel()
// All downstream calls respect this timeout
receipt, err := blockchain.SendTx(ctx, tx)
if err != nil {
return fmt.Errorf("send tx: %w", err) // error wrapping
}
return nil
}
Error Handling Philosophy: No exceptions. Errors are values.
result, err := doSomething()
if err != nil {
return fmt.Errorf("doing something: %w", err)
}
Always wrap errors with context. Use errors.Is() and errors.As() for comparison.Key Points
- ▸Goroutines are cheap (~2KB) — use them freely
- ▸Channels for safe communication between goroutines
- ▸Context carries timeouts and cancellation
- ▸Errors are values, not exceptions — always check and wrap
- ▸Select statement for multiplexing channel operations