samber/cc-skills-golang / skills/golang-data-structures
golang-data-structures
VerifiedGolang data structures — slices (internals, capacity growth, preallocation, slices package), maps (internals, hash buckets, maps package), arrays, container/list/heap/ring, strings.Builder vs bytes.Buffer, generic collections, pointers (unsafe.Pointer, weak.Pointer), and copy semantics. Use when choosing or optimizing Go data structures, implementing generic containers, using container/ packages, unsafe or weak pointers, or questioning slice/map internals. Not for applying optimization patterns once profiling has identified a bottleneck (→ See `samber/cc-skills-golang@golang-performance` skill).
| File | Kind | Size |
|---|---|---|
| SKILL.md | skill md | 10.4 KB |
| evals/evals.json | config | 19.6 KB |
| references/containers.md | markdown | 4.0 KB |
| references/generics.md | markdown | 2.5 KB |
| references/map-internals.md | markdown | 2.5 KB |
| references/pointers.md | markdown | 4.2 KB |
| references/slice-internals.md | markdown | 1.9 KB |
references/pointers.md
View on GitHub# Pointer Types Deep Dive
## Table of Contents
- [Regular Pointers (`*T`)](#regular-pointers-t)
- [Stack vs Heap (Escape Analysis)](#stack-vs-heap-escape-analysis)
- [`new(T)` vs `&T{}`](#newt-vs-t)
- [`unsafe.Pointer`](#unsafepointer)
- [The 6 Valid Patterns (from the Go spec)](#the-6-valid-patterns-from-the-go-spec)
- [Critical Rule: NEVER Store `uintptr` Across Statements](#critical-rule-never-store-uintptr-across-statements)
- [Modern Alternatives (prefer these)](#modern-alternatives-prefer-these)
- [`weak.Pointer[T]` (Go 1.24+)](#weakpointert-go-124)
- [Use Cases](#use-cases)
- [`runtime.AddCleanup` vs `runtime.SetFinalizer`](#runtimeaddcleanup-vs-runtimesetfinalizer)
## Regular Pointers (`*T`)
### Stack vs Heap (Escape Analysis)
Go's compiler decides whether to allocate on the stack or heap. A variable "escapes" to the heap when its lifetime extends beyond the function:
```go
func noEscape() int {
x := 42
return x // x stays on stack — copied on return
}
func escapes() *int {
x := 42
return &x // x escapes to heap — pointer outlives function
}
```
Use `go build -gcflags="-m"` to see escape analysis decisions. Heap allocations add GC pressure — avoid unnecessary escapes in hot paths.
### `new(T)` vs `&T{}`
Both allocate and return a pointer. `&T{}` is preferred because it allows field initialization:
```go
p := new(Point) // *Point with zero values
p := &Point{X: 1} // *Point with initialized fields — preferred
```
## `unsafe.Pointer`
`unsafe.Pointer` bypasses Go's type system for FFI and low-level memory manipulation. Only the 6 patterns from the Go spec are safe; any other pattern is undefined behavior.
### The 6 Valid Patterns (from the Go spec)
These are the ONLY safe ways to use `unsafe.Pointer`. Any other pattern is undefined behavior.
**Pattern 1: Convert `*T` to `*U` via `unsafe.Pointer`**
```go
// Reinterpret a float64 as its raw bits
f := 1.5
bits := *(*uint64)(unsafe.Pointer(&f))
```
**Pattern 2: Convert `unsafe.Pointer` to `uintptr` and back (same expression)**
```go
// Pointer arithmetic — MUST be a single expression
p := unsafe.Pointer(uintptr(unsafe.Pointer(&s.field)) + offset)
```
**Pattern 3: `reflect.Value.Pointer()` or `UnsafeAddr()` to `unsafe.Pointer`**
```go
p := unsafe.Pointer(reflect.ValueOf(&x).Pointer())
```
**Pattern 4: `syscall.Syscall` arguments**
```go
syscall.Syscall(SYS_READ, fd, uintptr(unsafe.Pointer(&buf[0])), uintptr(len(buf)))
```
### Critical Rule: NEVER Store `uintptr` Across Statements
```go
// ✗ DANGEROUS — GC can move the object between these two lines
u := uintptr(unsafe.Pointer(&x))
// ... GC may run here, moving x ...
p := unsafe.Pointer(u) // dangling pointer
// ✓ Safe — single expression
p := unsafe.Pointer(uintptr(unsafe.Pointer(&x)) + offset)
```
### Modern Alternatives (prefer these)
| Function | Since | Purpose |
| --- | --- | --- |
| `unsafe.Add(ptr, len)` | Go 1.17 | Pointer arithmetic without `uintptr` conversion |
| `unsafe.Slice(ptr, len)` | Go 1.17 | Create slice from pointer + length |
| `unsafe.String(ptr, len)` | Go 1.20 | Create string from pointer + length |
| `unsafe.SliceData(s)` | Go 1.17 | Get pointer to slice's backing array |
| `unsafe.StringData(s)` | Go 1.20 | Get pointer to string's backing array |
These are safer than manual `uintptr` arithmetic because they keep values as pointers (visible to GC) throughout.
## `weak.Pointer[T]` (Go 1.24+)
A weak pointer holds a reference to an object without preventing garbage collection. When the GC reclaims the object, `Value()` returns `nil`.
```go
strong := new(MyType)
w := weak.Make(strong)
if p := w.Value(); p != nil {
// object still alive
} else {
// object was garbage collected
}
```
### Use Cases
- **Deduplication caches** — intern equivalent values without preventing GC
- **Automatic cache eviction** — cached objects evict when no strong references remain
### `runtime.AddCleanup` vs `runtime.SetFinalizer`
Prefer `runtime.AddCleanup` (Go 1.24+) over `runtime.SetFinalizer`:
- Multiple cleanups can be registered per object
- Cleanup function receives a value, not a pointer to the collected object
- No risk of resurrecting the object
- Works correctly with weak pointers
Related skills
| Skill | Stars | Updated | Works with | Status | Install |
|---|---|---|---|---|---|
| reverse-engineer-anythingmorluto/reaReverse engineer native, managed, Electron/JavaScript, packaged, firmware, and browser targets with REA, and build agent environments (AgentEnv bundles) of web applications from a live instance or a capture, and of Linux desktop apps with a task from a request. Use shipped-artifact or requested runtime evidence to explain features, compare versions, decompile code, or guide a reconstruction. Skip REA for ordinary source-repository architecture analysis. | Stars: 472k | Updated | Claude CodeCodex | Verified | Install |
| diagnosing-superpowersobra/superpowersUse when a superpowers session went wrong and your human partner wants to know why — repeated work, ignored plans, stumbles, poor results, a skill that didn't fire, "it took too long", "why is it so expensive", "what is it doing" — or wants to build a bug report for the superpowers maintainers, for the current session or a past one identified by id or path, on any harness. | Stars: 322k | Updated | Claude CodeCodex | Verified | Install |
| dispatching-parallel-agentsobra/superpowersUse when facing 2+ independent tasks that can be worked on without shared state or sequential dependencies | Stars: 322k | Updated | Claude CodeCodex | Verified | Install |
| executing-plansobra/superpowersUse when executing an implementation plan in the current session as the implementer yourself — your human partner chose inline execution, or no subagent tool is available | Stars: 322k | Updated | Claude CodeCodex | Verified | Install |