Now liveThe Skillselion MCP - thousands of ranked skills, loaded into your agent mid-task. No install.Get it →
cxuu avatar

Go Defensive

  • 897 installs
  • 137 repo stars
  • Updated June 20, 2026
  • cxuu/golang-skills

go-defensive is a Go coding skill that enforces defensive copying of slices and maps at every API boundary so callers cannot mutate internal package state after a function returns.

About

go-defensive is a Go style skill from cxuu/golang-skills based on the Uber Style Guide for preventing accidental mutation of shared slice and map backing arrays at API boundaries. The skill shows bad patterns like assigning caller slices directly to struct fields and good patterns using make plus copy for slices and equivalent defensive copies for maps. Backend developers reach for go-defensive when writing setters, constructors, and repository methods that accept []T or map[K]V from external callers, tests, or HTTP handlers. Applying go-defensive early avoids subtle data races and state corruption in services where returned references would let callers modify internal collections after the function exits.

  • Prevents mutation bugs by copying slices and maps at API boundaries
  • Follows Uber Go Style Guide rules for receiving and returning reference types
  • Includes both slice copy via make+copy and map copy via range loop patterns
  • Applies to both inbound parameters and outbound return values
  • Works with mutex-protected internal state to avoid exposing mutable internals

Go Defensive by the numbers

  • 897 all-time installs (skills.sh)
  • +37 installs in the week ending Aug 4, 2026 (Skillselion tracking)
  • Ranked #446 of 4,347 Backend & APIs skills by installs in the Skillselion catalog
  • Security screen: LOW risk (skills.sh audit)
  • Data as of Aug 5, 2026 (Skillselion catalog sync)
npx skills add https://github.com/cxuu/golang-skills --skill go-defensive

Add your badge

Show developers this skill is listed on Skillselion. Paste this into your README.

Listed on Skillselion
Installs897
repo stars137
Security audit3 / 3 scanners passed
Last updatedJune 20, 2026
Repositorycxuu/golang-skills

How do you prevent slice mutation at Go API boundaries?

Enforce defensive copying of slices and maps at every Go API boundary so internal state cannot be accidentally mutated by callers.

Who is it for?

Go backend developers writing libraries or services that accept slices and maps from callers and must protect internal state.

Skip if: Teams working only with value-type structs, immutable protobuf messages, or languages without reference-type collections.

When should I use this skill?

A developer passes or stores []T or map[K]V parameters in Go structs and needs Uber-style defensive copy guidance.

What you get

Defensively copied slice and map fields in Go structs with make/copy patterns at every public API boundary.

  • Defensive copy implementations for slices and maps
  • Refactored setter methods

Files

SKILL.mdMarkdownGitHub ↗

Go Defensive Programming Patterns

Compatibility: Crypto examples may use crypto/rand.Text, which requires Go 1.24+.

Resource Routing

  • references/BOUNDARY-COPYING.md - Read when copying slices/maps across API boundaries.
  • references/GLOBAL-STATE.md - Read when introducing or removing package globals.
  • references/MUST-FUNCTIONS.md - Read when deciding whether a panic-on-error helper is acceptable.
  • references/PANIC-RECOVER.md - Read when evaluating panic, recover, or crash containment.
  • references/TIME-ENUMS-TAGS.md - Read when handling time types, enum zero values, or struct tags.

Defensive Checklist Priority

When hardening code at API boundaries, check in this order:

Reviewing an API boundary?
├─ 1. Error handling     → Return errors; don't panic (see go-error-handling)
├─ 2. Input validation   → Copy slices/maps received from callers
├─ 3. Output safety      → Copy slices/maps before returning to callers
├─ 4. Resource cleanup   → Use defer for Close/Unlock/Cancel
├─ 5. Interface checks   → Route compile-time assertions to go-interfaces
├─ 6. Time correctness   → Use time.Time and time.Duration, not int/float
├─ 7. Enum safety        → Start iota at 1 so zero-value is invalid
└─ 8. Crypto safety      → crypto/rand for keys, never math/rand

---

Quick Reference

PatternRuleDetails
Boundary copiesCopy slices/maps on receive and returnBOUNDARY-COPYING.md
Defer cleanupdefer f.Close() right after os.OpenBelow
Interface checkCompile-time satisfaction assertionSee go-interfaces
Time typestime.Time / time.Duration, never raw intTIME-ENUMS-TAGS.md
Enum startiota + 1 so zero = invalidBelow
Crypto randcrypto/rand for keys, never math/randBelow
Must functionsOnly at init; panic on failureMUST-FUNCTIONS.md
Panic/recoverNever expose panics across packagesPANIC-RECOVER.md
Mutable globalsReplace with dependency injectionBelow

---

Verify Interface Compliance

Route compile-time interface assertions to go-interfaces. Use this skill only to notice API-boundary robustness risk; the interface skill owns when an assertion is appropriate and the exact assertion shape.

Copy Slices and Maps at Boundaries

Slices and maps contain pointers to underlying data. Copy at API boundaries to prevent unintended modifications.

// Receiving: copy incoming slice
d.trips = make([]Trip, len(trips))
copy(d.trips, trips)

// Returning: copy map before returning
result := make(map[string]int, len(s.counters))
for k, v := range s.counters { result[k] = v }

Defer to Clean Up

Use defer to clean up resources (files, locks). Avoids missed cleanup on multiple return paths.

p.Lock()
defer p.Unlock()

if p.count < 10 {
  return p.count
}
p.count++
return p.count

Defer overhead is negligible. Place defer f.Close() immediately after os.Open for clarity. Arguments to deferred functions are evaluated when defer executes, not when the function runs. Multiple defers execute in LIFO order.

Struct Field Tags

Advisory: Always add explicit field tags to structs that are marshaled or unmarshaled.
type User struct {
    Name  string `json:"name"  yaml:"name"`
    Email string `json:"email" yaml:"email"`
}

Field tags are a serialization contract — renaming a struct field without updating the tag silently breaks wire compatibility. Treat tags as part of the public API for any type that crosses a serialization boundary.

Start Enums at One

Start enums at non-zero to distinguish uninitialized from valid values.

const (
  Add Operation = iota + 1  // Add=1, zero value = uninitialized
  Subtract
  Multiply
)

Exception: When zero is the sensible default (e.g., LogToStdout = iota).

Time, Struct Tags, and Embedding

Avoid Mutable Globals

Inject dependencies instead of mutating package-level variables. This makes code testable without global save/restore.

type signer struct {
  now func() time.Time  // injected; tests replace with fixed time
}

func newSigner() *signer {
  return &signer{now: time.Now}
}

Crypto Rand

Do not use math/rand or math/rand/v2 to generate keys — this is a security concern. Time-seeded generators have predictable output.

import "crypto/rand"

func Key() string { return rand.Text() }

For text output, use crypto/rand.Text directly, or encode random bytes with encoding/hex or encoding/base64.

---

Panic and Recover

Use panic only for truly unrecoverable situations. Library functions should avoid panic.

func safelyDo(work *Work) {
    defer func() {
        if err := recover(); err != nil {
            log.Println("work failed:", err)
        }
    }()
    do(work)
}

Key rules:

  • Never expose panics across package boundaries — always convert to errors
  • Acceptable to panic in init() if a library truly cannot set itself up
  • Use recover to isolate panics in server goroutine handlers

Must Functions

Must functions panic on error — use them only during program initialization where failure means the program cannot run.

var validID = regexp.MustCompile(`^[a-z][a-z0-9-]{0,62}$`)
var tmpl = template.Must(template.ParseFiles("index.html"))

---

Related Skills

  • Error handling: See go-error-handling when choosing between returning errors and panicking, or wrapping errors at boundaries
  • Concurrency safety: See go-concurrency when protecting shared state with mutexes, atomics, or channels
  • Interface checks: See go-interfaces when adding compile-time interface satisfaction checks
  • Data structure copying: See go-data-structures when working with slice/map internals or pointer aliasing

Related skills

How it compares

Use go-defensive for concrete Go slice and map copy patterns rather than general immutability guides that do not show struct-boundary code.

FAQ

Why does go-defensive require copying slices in Go?

go-defensive follows the Uber Go Style Guide because slices and maps hold references to shared backing arrays. Assigning a caller slice directly to a struct field lets the caller mutate internal state after the function returns.

What Go pattern does go-defensive recommend for slices?

go-defensive recommends make([]Trip, len(trips)) followed by copy(d.trips, trips) in setters instead of direct assignment. This creates an independent backing array the caller cannot modify.

Is Go Defensive safe to install?

skills.sh reports 3 of 3 security scanners passed. Review the Security Audits panel on this page before installing in production.

Backend & APIsbackendintegrations

This week in AI coding

Five minutes, every Monday - the tools, releases and tactics for developers.

unsubscribe anytime.