go-data-structures
Use when creating or manipulating Go slices, maps, arrays, or sets, including new/make, append, copies, and nil versus empty JSON collections. Thread safety belongs to go-concurrency.
- License 许可
- Apache-2.0
- 最近更新
- 2026-11-14
- Stars
- ★ 7
- Forks
- 2
01 前言 Front Matter
- name
- go-data-structures
- description
- Use when creating or manipulating Go slices, maps, arrays, or sets, including new/make, append, copies, and nil versus empty JSON collections. Thread safety belongs to go-concurrency.
02 资源文件 1
- 参考文档references/SLICES.md1.1 KB
03 SKILL.md 正文
Go Data Structures
Compatibility: Baseline Go 1.27 (see COMPATIBILITY.md).
slices/mapsandslices.Clone/maps.Clonerequire Go 1.21+;slices.ConcatGo 1.22+;strings.CutLast/bytes.CutLastGo 1.27+.
Resource Routing
references/SLICES.md- Read when managing slice capacity and aliasing, or when a subslice keeps a large backing array alive.
Slices
Reach for slices and maps First
The slices and maps packages (Go 1.21+) cover most hand-written loops.
Writing the loop instead is a reviewable defect, not a style choice.
go fix -diff on the edited package previews the loops a fixer exists for
(slicescontains, slicesbackward, slicessort, mapsloop, minmax);
Equal, Concat, Insert, and Delete have none: replace those loops
yourself.
| Loop you were about to write | Use |
|---|---|
| Compare | slices.Equal, maps.Equal |
| Concatenate | slices.Concat (Go 1.22+) |
| Insert/delete in the middle | slices.Insert, slices.Delete |
| Iterate in reverse | slices.Backward (Go 1.23+) |
| Split off the last segment | strings.CutLast / bytes.CutLast (Go 1.27+) |
ns, name, ok := strings.CutLast(key, ".") // "app.http.requests" → "app.http", "requests", true
if !ok {
ns, name = "", key // no ".": CutLast returned key, "", false
}
slices.Clone and maps.Clone preserve nilness: nil input yields nil, while
an initialized empty container stays non-nil. slices.Collect,
slices.Sorted, and slices.Concat return nil for an empty result —
Concat even when every input is a non-nil empty slice. An unconditional
make plus copy produces a non-nil container even for nil input. Preserve
that allocation when JSON, a later map write, or observable capacity requires
it — see Declaring Empty Slices. Check the contract
before replacing a loop:
all := slices.Concat(a, b)
if all == nil {
all = []Item{} // encoding/json v1 writes nil as null; this list's contract is []
}
These clones are shallow: references inside elements or map values remain
shared. Copy depth and type-specific Clone contracts belong to
go-defensive.
Update and Filter an Existing Map
When updates must overwrite matching keys before filtering the resulting map:
maps.Copy(dst, updates)
maps.DeleteFunc(dst, func(_ string, score int) bool { return score < minimum })
Both operations mutate dst, so existing aliases observe the changes.
The destination must be initialized if the source contains entries.
Declaring Empty Slices
Prefer nil slices over empty literals:
// Good: nil slice
var t []string
// Avoid: non-nil but zero-length
t := []string{}
Both have len and cap of zero, but the nil slice is the preferred style.
JSON depends on the encoder: encoding/json v1 encodes a nil slice or
nil map as null, and []string{} as [], map[string]int{} as {}. JSON
v2 defaults encode nil non-byte slices as [] and nil maps as {};
FormatNilSliceAsNull(true) and FormatNilMapAsNull(true) restore null.
Require non-nil only when the selected encoder/options or another caller
contract needs it. See
JSON v2 defaults.
When designing interfaces, avoid distinguishing between nil and non-nil zero-length slices.
Maps
Implementing a Set
Use map[T]struct{} when the map is only a set. The empty struct takes no
storage and makes membership intent explicit.
Use boolean map values only when the value carries a separate meaning beyond presence.
A Map Never Shrinks
delete and clear free the values but keep the table at its peak size
(measured on Go 1.27: 500K keys at 30 MiB stay at 26 MiB after either). A map
whose size swings — per-window counters, a swept cache, a limiter reset — is
reset by assigning a fresh make, and the old one is collected.
Copying
A struct whose methods have pointer receivers or that holds a lock
(bytes.Buffer, sync.Mutex) is passed by pointer, never copied — except a
value type whose only pointer methods are decoders, such as time.Time;
go-functions owns the rule.
Related Skills
- go-defensive: copying slices and maps at API boundaries.
- go-performance: capacity hints for known workloads.
- go-style-core: range forms and
new/make/var/literal choices.
04 同仓库更多 Skills
go-troubleshooting
Use when investigating a bug or ticket in a Go service whose cause is unknown — wrong or missing results, tenant-specific behavior, a regression, stage/prod/CI differences, a panic, hang, deadlock, leak, unexplained CPU/RSS growth, or a flaky test. Also use for pasted stack traces, profiles, logs, or requests to find a Go issue's root cause, even without the word debug. Does not cover rewriting ticket text, implementing an already-diagnosed fix alone (use its topic skill), or optimizing a known bottleneck (see go-performance).
go-testing
Use when writing, reviewing, or improving Go test code — including table-driven tests, subtests, parallel tests, test helpers, test doubles, and assertions with cmp.Diff. Also use when a user asks to write a test for a Go function, even if they don't mention specific patterns like table-driven tests or subtests. Does not cover benchmark performance testing (see go-performance).
go-style-core
Use when resolving Go style or language mechanics such as formatting, nesting, declarations, initialization, scope, shadowing, loops, switches, or enum zero values. API design, naming, errors, and tests have specialized skills.
go-security
Use when writing or reviewing Go code that touches untrusted input, secrets, or credentials — SQL, shell, or template injection, path traversal, SSRF, cookies and security headers, password hashing, TLS settings, token comparison, or what may appear in a log line. Also use when a handler accepts a file name, URL, or command argument from a client, or when asked to find "vulnerabilities", even if the user never says "security". Does not cover the os.Root and crypto/rand mechanics (see go-defensive) or the dependency CVE scan in the gate (see go-linting).
go-resilience
Use when handling Go dependency failures or overload with retries, backoff/jitter, budgets, idempotency, duplicate delivery, circuit breakers, bulkheads, rate limits, backpressure, or degradation. Unknown root causes belong to go-troubleshooting.
go-performance
Use when optimizing slow or performance-critical Go code, allocations, string concatenation in loops, or benchmarks. Also use when writing or reviewing a cache, including implementing one from a stub — its key, its expiry, and how a miss loads. Concurrent code patterns belong to go-concurrency.