go-defensivelisted
Install: claude install-skill dwana1/golang-skills
# Go Defensive Programming Patterns
## Verify Interface Compliance
> **Source**: Uber Go Style Guide
Verify interface compliance at compile time using zero-value assertions.
**Bad**
```go
type Handler struct{}
func (h *Handler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
// ...
}
```
**Good**
```go
type Handler struct{}
var _ http.Handler = (*Handler)(nil)
func (h *Handler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
// ...
}
```
Use `nil` for pointer types, slices, maps; empty struct `{}` for value receivers.
## Copy Slices and Maps at Boundaries
> **Source**: Uber Go Style Guide
Slices and maps contain pointers. Copy at API boundaries to prevent unintended modifications.
### Receiving
**Bad**
```go
func (d *Driver) SetTrips(trips []Trip) {
d.trips = trips // caller can still modify d.trips
}
```
**Good**
```go
func (d *Driver) SetTrips(trips []Trip) {
d.trips = make([]Trip, len(trips))
copy(d.trips, trips)
}
```
### Returning
**Bad**
```go
func (s *Stats) Snapshot() map[string]int {
s.mu.Lock()
defer s.mu.Unlock()
return s.counters // exposes internal state!
}
```
**Good**
```go
func (s *Stats) Snapshot() map[string]int {
s.mu.Lock()
defer s.mu.Unlock()
result := make(map[string]int, len(s.counters))
for k, v := range s.counters {
result[k] = v
}
return result
}
```
## Defer to Clean Up
> **Source**: Uber Go Style Guide, Effective Go
Use `defer` to clean up resources (files, locks). Avoids missed cleanup