返回 Skills
cxuu/golang-skills· Apache-2.0 内容可用

go-data-structures

Use when working with Go slices, maps, or arrays — choosing between new and make, using append, declaring empty slices (nil vs literal for JSON), implementing sets with maps, and copying data at boundaries. Also use when building or manipulating collections, even if the user doesn't ask about allocation idioms. Does not cover concurrent data structure safety (see go-concurrency).

安装

与 skills.sh 相同的 Command / Prompt 安装方式


name: go-data-structures description: Use when working with Go slices, maps, or arrays — choosing between new and make, using append, declaring empty slices (nil vs literal for JSON), implementing sets with maps, and copying data at boundaries. Also use when building or manipulating collections, even if the user doesn't ask about allocation idioms. Does not cover concurrent data structure safety (see go-concurrency).

Go Data Structures

Resource Routing

  • references/SLICES.md - Read when deciding nil versus empty slices, copying slices, or managing slice capacity and aliasing.

Choosing a Data Structure

What do you need?
├─ Ordered collection of items
│  ├─ Fixed size known at compile time → Array [N]T
│  └─ Dynamic size → Slice []T
│     ├─ Know approximate size? → make([]T, 0, capacity)
│     └─ Unknown size or nil-safe for JSON? → var s []T (nil)
├─ Key-value lookup
│  └─ Map map[K]V
│     ├─ Know approximate size? → make(map[K]V, capacity)
│     └─ Need a set? → map[T]struct{} (zero-size values)
└─ Need to pass to a function?
   └─ Copy at the boundary if the caller might mutate it

When this skill does NOT apply: For concurrent access to data structures (mutexes, atomic operations), see go-concurrency. For defensive copying at API boundaries, see go-defensive. For pre-sizing capacity for performance, see go-performance.


Slices

The append Function

Always assign the result — the underlying array may change:

x := []int{1, 2, 3}
x = append(x, 4, 5, 6)

// Append a slice to a slice
x = append(x, y...)  // Note the ...

Two-Dimensional Slices

Independent inner slices (can grow/shrink independently):

picture := make([][]uint8, YSize)
for i := range picture {
    picture[i] = make([]uint8, XSize)
}

Single allocation (more efficient for fixed sizes):

picture := make([][]uint8, YSize)
pixels := make([]uint8, XSize*YSize)
for i := range picture {
    picture[i], pixels = pixels[:XSize], pixels[XSize:]
}

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.

Exception for JSON: A nil slice encodes to null, while []string{} encodes to []. Use non-nil when you need a JSON array.

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:

attended := map[string]struct{}{"Ann": {}, "Joe": {}}
if _, ok := attended[person]; ok {
    fmt.Println(person, "was at the meeting")
}

Use boolean map values only when the value carries a separate meaning beyond presence.


Copying

Be careful when copying a struct from another package. If the type has methods on its pointer type (*T), copying the value can cause aliasing bugs.

General rule: Do not copy a value of type T if its methods are associated with the pointer type *T. This applies to bytes.Buffer, sync.Mutex, sync.WaitGroup, and types containing them.

// Bad: copying a mutex
var mu sync.Mutex
mu2 := mu  // almost always a bug

// Good: pass by pointer
func increment(sc *SafeCounter) {
    sc.mu.Lock()
    sc.count++
    sc.mu.Unlock()
}

Quick Reference

TopicKey Point
SlicesAlways assign append result; nil slice preferred over []T{}
Setsmap[T]struct{} for membership-only sets
CopyingDon't copy T if methods are on *T; beware aliasing

Related Skills

  • Defensive copying: See go-defensive when copying slices or maps at API boundaries to prevent mutation
  • Capacity hints: See go-performance when pre-sizing slices or maps for known workloads
  • Iteration patterns: See go-control-flow when using range loops over slices, maps, or channels
  • Declaration style: See go-declarations when choosing between new, make, var, and composite literals

附带文件

references/SLICES.md
# Go Slice Internals

> **Source**: Effective Go

---

## The Three-Item Descriptor

A slice is a runtime data structure with three components:

- **Pointer**: Address of the first accessible element
- **Length**: Number of elements (`len(s)`)
- **Capacity**: Max elements to end of underlying array (`cap(s)`)

```go
arr := [5]int{10, 20, 30, 40, 50}
s := arr[1:4]  // s = [20, 30, 40]
// pointer: &arr[1], length: 3, capacity: 4
```

A `nil` slice has all three items set to zero/nil.

---

## Slices Reference Underlying Arrays

Slices don't store data—they describe a section of an array:

```go
data := [4]int{1, 2, 3, 4}
a := data[0:2]  // [1, 2]
b := data[1:3]  // [2, 3]

b[0] = 99
fmt.Println(a)    // [1, 99] - both see the change
fmt.Println(data) // [1, 99, 3, 4]
```

---

## The Slice Operator

`s[lo:hi]` creates a slice from index `lo` to `hi-1`:

```go
s := []int{0, 1, 2, 3, 4, 5}
s[2:4]   // [2, 3]
s[:3]    // [0, 1, 2]
s[3:]    // [3, 4, 5]
```

Three-index form `s[lo:hi:max]` limits capacity to `max-lo`.

---

## Why append Must Return the Slice

The slice header is passed **by value**. Functions can modify elements but
cannot change the caller's header:

```go
func Append(slice, data []byte) []byte {
    l := len(slice)
    if l+len(data) > cap(slice) {
        newSlice := make([]byte, (l+len(data))*2)
        copy(newSlice, slice)
        slice = newSlice  // Only changes local variable
    }
    slice = slice[0 : l+len(data)]
    copy(slice[l:], data)
    return slice  // Caller must receive the new header
}
```

When reallocation occurs, `slice` points to a new array. The caller's original
still points to the old one—returning lets them update their reference.

---

## The copy Function

`copy(dst, src)` copies elements and returns the count copied:

```go
src := []int{1, 2, 3, 4, 5}
dst := make([]int, 3)
n := copy(dst, src)  // n=3, dst=[1,2,3]
```

Handles overlapping slices correctly. Copies `min(len(dst), len(src))`
elements—no reallocation occurs.

---

## Slice Gotchas

### 1. Shared Underlying Array

```go
original := []int{1, 2, 3, 4, 5}
subset := original[1:3]
subset[0] = 99
fmt.Println(original)  // [1, 99, 3, 4, 5] - modified!

// Fix: make independent copy
subset := make([]int, 2)
copy(subset, original[1:3])
```

### 2. Append May or May Not Reallocate

```go
a := make([]int, 3, 5)  // len=3, cap=5
b := a[0:3]
a = append(a, 4)    // Fits in capacity - still shared
a = append(a, 5, 6) // Exceeds capacity - now independent
```

### 3. Memory Leaks from Large Backing Arrays

```go
// Bad: small slice keeps entire file in memory
func getHeader(file []byte) []byte { return file[:100] }

// Good: copy to release the large array
func getHeader(file []byte) []byte {
    header := make([]byte, 100)
    copy(header, file)
    return header
}
```

### 4. Nil vs Empty Slice

```go
var nilSlice []int     // nil, len=0, cap=0
emptySlice := []int{}  // non-nil, len=0, cap=0
// Both work identically with len, cap, append, range
// Prefer nil for uninitialized state
```

## Quick Reference

| Operation | Behavior |
|-----------|----------|
| `s[lo:hi]` | Slice from lo to hi-1 |
| `s[lo:hi:max]` | Slice with capacity limited to max-lo |
| `append(s, x...)` | Returns new slice; may reallocate |
| `copy(dst, src)` | Returns count copied; no reallocation |
    go-data-structures | Prompt Minder