Go学习笔记-Generics

泛型是Go 1.18引入的重要特性,它允许编写类型安全且可重用的代码。泛型通过类型参数实现,可以在编译时进行类型检查,同时避免运行时的类型断言开销。

基本泛型语法

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
package main

import (
    "fmt"
    "constraints"
    "sync"
)

// 1. 基本泛型函数
func Max[T constraints.Ordered](a, b T) T {
    if a > b {
        return a
    }
    return b
}

func Min[T constraints.Ordered](a, b T) T {
    if a < b {
        return a
    }
    return b
}

// 2. 多类型参数的泛型函数
func Pair[T, U any](first T, second U) (T, U) {
    return first, second
}

// 3. 泛型切片操作
func Map[T, U any](slice []T, fn func(T) U) []U {
    result := make([]U, len(slice))
    for i, v := range slice {
        result[i] = fn(v)
    }
    return result
}

func Filter[T any](slice []T, predicate func(T) bool) []T {
    var result []T
    for _, v := range slice {
        if predicate(v) {
            result = append(result, v)
        }
    }
    return result
}

func Reduce[T, U any](slice []T, initial U, fn func(U, T) U) U {
    result := initial
    for _, v := range slice {
        result = fn(result, v)
    }
    return result
}

// 4. 泛型查找函数
func Find[T comparable](slice []T, target T) (int, bool) {
    for i, v := range slice {
        if v == target {
            return i, true
        }
    }
    return -1, false
}

func Contains[T comparable](slice []T, target T) bool {
    _, found := Find(slice, target)
    return found
}

// 5. 泛型排序
func BubbleSort[T constraints.Ordered](slice []T) {
    n := len(slice)
    for i := 0; i < n-1; i++ {
        for j := 0; j < n-i-1; j++ {
            if slice[j] > slice[j+1] {
                slice[j], slice[j+1] = slice[j+1], slice[j]
            }
        }
    }
}

func main() {
    // 1. 基本泛型函数使用
    fmt.Println("=== 基本泛型函数 ===")
    
    // 整数比较
    fmt.Printf("Max(10, 20) = %d\n", Max(10, 20))
    fmt.Printf("Min(10, 20) = %d\n", Min(10, 20))
    
    // 浮点数比较
    fmt.Printf("Max(3.14, 2.71) = %.2f\n", Max(3.14, 2.71))
    fmt.Printf("Min(3.14, 2.71) = %.2f\n", Min(3.14, 2.71))
    
    // 字符串比较
    fmt.Printf("Max(\"apple\", \"banana\") = %s\n", Max("apple", "banana"))
    fmt.Printf("Min(\"apple\", \"banana\") = %s\n", Min("apple", "banana"))
    
    // 2. 多类型参数
    fmt.Println("\n=== 多类型参数 ===")
    
    intStr := Pair(42, "hello")
    fmt.Printf("Pair(42, \"hello\") = %v\n", intStr)
    
    floatBool := Pair(3.14, true)
    fmt.Printf("Pair(3.14, true) = %v\n", floatBool)
    
    // 3. 泛型切片操作
    fmt.Println("\n=== 泛型切片操作 ===")
    
    numbers := []int{1, 2, 3, 4, 5}
    
    // Map操作:平方
    squares := Map(numbers, func(x int) int {
        return x * x
    })
    fmt.Printf("平方: %v -> %v\n", numbers, squares)
    
    // Map操作:转换为字符串
    strings := Map(numbers, func(x int) string {
        return fmt.Sprintf("num_%d", x)
    })
    fmt.Printf("转字符串: %v -> %v\n", numbers, strings)
    
    // Filter操作:过滤偶数
    evens := Filter(numbers, func(x int) bool {
        return x%2 == 0
    })
    fmt.Printf("偶数: %v -> %v\n", numbers, evens)
    
    // Reduce操作:求和
    sum := Reduce(numbers, 0, func(acc, x int) int {
        return acc + x
    })
    fmt.Printf("求和: %v -> %d\n", numbers, sum)
    
    // Reduce操作:求积
    product := Reduce(numbers, 1, func(acc, x int) int {
        return acc * x
    })
    fmt.Printf("求积: %v -> %d\n", numbers, product)
    
    // 4. 查找操作
    fmt.Println("\n=== 查找操作 ===")
    
    fruits := []string{"apple", "banana", "cherry", "date"}
    
    if index, found := Find(fruits, "cherry"); found {
        fmt.Printf("找到 'cherry' 在索引 %d\n", index)
    } else {
        fmt.Println("未找到 'cherry'")
    }
    
    fmt.Printf("包含 'banana': %t\n", Contains(fruits, "banana"))
    fmt.Printf("包含 'grape': %t\n", Contains(fruits, "grape"))
    
    // 5. 泛型排序
    fmt.Println("\n=== 泛型排序 ===")
    
    intSlice := []int{64, 34, 25, 12, 22, 11, 90}
    fmt.Printf("排序前: %v\n", intSlice)
    BubbleSort(intSlice)
    fmt.Printf("排序后: %v\n", intSlice)
    
    floatSlice := []float64{3.14, 2.71, 1.41, 1.73}
    fmt.Printf("排序前: %v\n", floatSlice)
    BubbleSort(floatSlice)
    fmt.Printf("排序后: %v\n", floatSlice)
    
    stringSlice := []string{"zebra", "apple", "banana", "cherry"}
    fmt.Printf("排序前: %v\n", stringSlice)
    BubbleSort(stringSlice)
    fmt.Printf("排序后: %v\n", stringSlice)
}

泛型类型和约束

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
package main

import (
    "fmt"
    "constraints"
)

// 1. 自定义约束
type Numeric interface {
    ~int | ~int8 | ~int16 | ~int32 | ~int64 |
    ~uint | ~uint8 | ~uint16 | ~uint32 | ~uint64 |
    ~float32 | ~float64
}

type Stringer interface {
    String() string
}

// 2. 泛型结构体
type Stack[T any] struct {
    items []T
}

func NewStack[T any]() *Stack[T] {
    return &Stack[T]{
        items: make([]T, 0),
    }
}

func (s *Stack[T]) Push(item T) {
    s.items = append(s.items, item)
}

func (s *Stack[T]) Pop() (T, bool) {
    if len(s.items) == 0 {
        var zero T
        return zero, false
    }
    
    index := len(s.items) - 1
    item := s.items[index]
    s.items = s.items[:index]
    return item, true
}

func (s *Stack[T]) Peek() (T, bool) {
    if len(s.items) == 0 {
        var zero T
        return zero, false
    }
    
    return s.items[len(s.items)-1], true
}

func (s *Stack[T]) Size() int {
    return len(s.items)
}

func (s *Stack[T]) IsEmpty() bool {
    return len(s.items) == 0
}

// 3. 泛型队列
type Queue[T any] struct {
    items []T
}

func NewQueue[T any]() *Queue[T] {
    return &Queue[T]{
        items: make([]T, 0),
    }
}

func (q *Queue[T]) Enqueue(item T) {
    q.items = append(q.items, item)
}

func (q *Queue[T]) Dequeue() (T, bool) {
    if len(q.items) == 0 {
        var zero T
        return zero, false
    }
    
    item := q.items[0]
    q.items = q.items[1:]
    return item, true
}

func (q *Queue[T]) Size() int {
    return len(q.items)
}

// 4. 泛型映射
type SafeMap[K comparable, V any] struct {
    data map[K]V
    mu   sync.RWMutex
}

func NewSafeMap[K comparable, V any]() *SafeMap[K, V] {
    return &SafeMap[K, V]{
        data: make(map[K]V),
    }
}

func (sm *SafeMap[K, V]) Set(key K, value V) {
    sm.mu.Lock()
    defer sm.mu.Unlock()
    sm.data[key] = value
}

func (sm *SafeMap[K, V]) Get(key K) (V, bool) {
    sm.mu.RLock()
    defer sm.mu.RUnlock()
    value, exists := sm.data[key]
    return value, exists
}

func (sm *SafeMap[K, V]) Delete(key K) {
    sm.mu.Lock()
    defer sm.mu.Unlock()
    delete(sm.data, key)
}

func (sm *SafeMap[K, V]) Size() int {
    sm.mu.RLock()
    defer sm.mu.RUnlock()
    return len(sm.data)
}

// 5. 泛型链表节点
type Node[T any] struct {
    Value T
    Next  *Node[T]
}

type LinkedList[T any] struct {
    head *Node[T]
    size int
}

func NewLinkedList[T any]() *LinkedList[T] {
    return &LinkedList[T]{}
}

func (ll *LinkedList[T]) Add(value T) {
    newNode := &Node[T]{Value: value}
    
    if ll.head == nil {
        ll.head = newNode
    } else {
        current := ll.head
        for current.Next != nil {
            current = current.Next
        }
        current.Next = newNode
    }
    ll.size++
}

func (ll *LinkedList[T]) Remove(value T) bool {
    if ll.head == nil {
        return false
    }
    
    // 如果要删除的是头节点
    if any(ll.head.Value) == any(value) {
        ll.head = ll.head.Next
        ll.size--
        return true
    }
    
    current := ll.head
    for current.Next != nil {
        if any(current.Next.Value) == any(value) {
            current.Next = current.Next.Next
            ll.size--
            return true
        }
        current = current.Next
    }
    
    return false
}

func (ll *LinkedList[T]) ToSlice() []T {
    result := make([]T, 0, ll.size)
    current := ll.head
    
    for current != nil {
        result = append(result, current.Value)
        current = current.Next
    }
    
    return result
}

func (ll *LinkedList[T]) Size() int {
    return ll.size
}

// 6. 数学运算函数
func Add[T Numeric](a, b T) T {
    return a + b
}

func Multiply[T Numeric](a, b T) T {
    return a * b
}

func Average[T Numeric](numbers []T) T {
    if len(numbers) == 0 {
        var zero T
        return zero
    }
    
    var sum T
    for _, num := range numbers {
        sum += num
    }
    
    return sum / T(len(numbers))
}

func main() {
    // 1. 泛型栈使用
    fmt.Println("=== 泛型栈 ===")
    
    intStack := NewStack[int]()
    intStack.Push(1)
    intStack.Push(2)
    intStack.Push(3)
    
    fmt.Printf("栈大小: %d\n", intStack.Size())
    
    if value, ok := intStack.Peek(); ok {
        fmt.Printf("栈顶元素: %d\n", value)
    }
    
    for !intStack.IsEmpty() {
        if value, ok := intStack.Pop(); ok {
            fmt.Printf("弹出: %d\n", value)
        }
    }
    
    // 字符串栈
    stringStack := NewStack[string]()
    stringStack.Push("hello")
    stringStack.Push("world")
    
    for !stringStack.IsEmpty() {
        if value, ok := stringStack.Pop(); ok {
            fmt.Printf("弹出字符串: %s\n", value)
        }
    }
    
    // 2. 泛型队列使用
    fmt.Println("\n=== 泛型队列 ===")
    
    queue := NewQueue[string]()
    queue.Enqueue("first")
    queue.Enqueue("second")
    queue.Enqueue("third")
    
    fmt.Printf("队列大小: %d\n", queue.Size())
    
    for queue.Size() > 0 {
        if value, ok := queue.Dequeue(); ok {
            fmt.Printf("出队: %s\n", value)
        }
    }
    
    // 3. 安全映射使用
    fmt.Println("\n=== 安全映射 ===")
    
    safeMap := NewSafeMap[string, int]()
    safeMap.Set("apple", 5)
    safeMap.Set("banana", 3)
    safeMap.Set("cherry", 8)
    
    if value, exists := safeMap.Get("apple"); exists {
        fmt.Printf("apple: %d\n", value)
    }
    
    fmt.Printf("映射大小: %d\n", safeMap.Size())
    
    safeMap.Delete("banana")
    fmt.Printf("删除banana后大小: %d\n", safeMap.Size())
    
    // 4. 泛型链表使用
    fmt.Println("\n=== 泛型链表 ===")
    
    list := NewLinkedList[int]()
    list.Add(1)
    list.Add(2)
    list.Add(3)
    list.Add(4)
    
    fmt.Printf("链表内容: %v\n", list.ToSlice())
    fmt.Printf("链表大小: %d\n", list.Size())
    
    list.Remove(2)
    fmt.Printf("删除2后: %v\n", list.ToSlice())
    
    // 5. 数学运算
    fmt.Println("\n=== 数学运算 ===")
    
    fmt.Printf("Add(10, 20) = %d\n", Add(10, 20))
    fmt.Printf("Add(3.14, 2.86) = %.2f\n", Add(3.14, 2.86))
    
    fmt.Printf("Multiply(5, 6) = %d\n", Multiply(5, 6))
    fmt.Printf("Multiply(2.5, 4.0) = %.1f\n", Multiply(2.5, 4.0))
    
    intNumbers := []int{1, 2, 3, 4, 5}
    fmt.Printf("Average(%v) = %d\n", intNumbers, Average(intNumbers))
    
    floatNumbers := []float64{1.5, 2.5, 3.5, 4.5}
    fmt.Printf("Average(%v) = %.1f\n", floatNumbers, Average(floatNumbers))
}

泛型的高级特性

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
package main

import (
    "fmt"
    "reflect"
)

// 1. 类型推断
func TypeInference() {
    fmt.Println("=== 类型推断 ===")
    
    // 编译器可以推断类型参数
    result1 := Max(10, 20)        // 推断为Max[int]
    result2 := Max(3.14, 2.71)    // 推断为Max[float64]
    result3 := Max("a", "b")      // 推断为Max[string]
    
    fmt.Printf("Max(10, 20) = %d (类型: %T)\n", result1, result1)
    fmt.Printf("Max(3.14, 2.71) = %.2f (类型: %T)\n", result2, result2)
    fmt.Printf("Max(\"a\", \"b\") = %s (类型: %T)\n", result3, result3)
}

// 2. 类型约束组合
type SignedInteger interface {
    ~int | ~int8 | ~int16 | ~int32 | ~int64
}

type UnsignedInteger interface {
    ~uint | ~uint8 | ~uint16 | ~uint32 | ~uint64
}

type Integer interface {
    SignedInteger | UnsignedInteger
}

type Float interface {
    ~float32 | ~float64
}

type Number interface {
    Integer | Float
}

// 3. 方法约束
type Comparable[T any] interface {
    Compare(T) int
}

type Person struct {
    Name string
    Age  int
}

func (p Person) Compare(other Person) int {
    if p.Age < other.Age {
        return -1
    } else if p.Age > other.Age {
        return 1
    }
    return 0
}

func Sort[T Comparable[T]](slice []T) {
    n := len(slice)
    for i := 0; i < n-1; i++ {
        for j := 0; j < n-i-1; j++ {
            if slice[j].Compare(slice[j+1]) > 0 {
                slice[j], slice[j+1] = slice[j+1], slice[j]
            }
        }
    }
}

// 4. 泛型接口
type Container[T any] interface {
    Add(T)
    Remove(T) bool
    Contains(T) bool
    Size() int
    Clear()
}

type Set[T comparable] struct {
    data map[T]struct{}
}

func NewSet[T comparable]() *Set[T] {
    return &Set[T]{
        data: make(map[T]struct{}),
    }
}

func (s *Set[T]) Add(item T) {
    s.data[item] = struct{}{}
}

func (s *Set[T]) Remove(item T) bool {
    if _, exists := s.data[item]; exists {
        delete(s.data, item)
        return true
    }
    return false
}

func (s *Set[T]) Contains(item T) bool {
    _, exists := s.data[item]
    return exists
}

func (s *Set[T]) Size() int {
    return len(s.data)
}

func (s *Set[T]) Clear() {
    s.data = make(map[T]struct{})
}

func (s *Set[T]) ToSlice() []T {
    result := make([]T, 0, len(s.data))
    for item := range s.data {
        result = append(result, item)
    }
    return result
}

// 5. 泛型函数类型
type Predicate[T any] func(T) bool
type Transformer[T, U any] func(T) U
type Reducer[T, U any] func(U, T) U

// 高阶函数
func FilterMap[T, U any](slice []T, predicate Predicate[T], transformer Transformer[T, U]) []U {
    var result []U
    for _, item := range slice {
        if predicate(item) {
            result = append(result, transformer(item))
        }
    }
    return result
}

// 6. 泛型方法
type Calculator[T Number] struct {
    history []T
}

func NewCalculator[T Number]() *Calculator[T] {
    return &Calculator[T]{
        history: make([]T, 0),
    }
}

func (c *Calculator[T]) Add(a, b T) T {
    result := a + b
    c.history = append(c.history, result)
    return result
}

func (c *Calculator[T]) Multiply(a, b T) T {
    result := a * b
    c.history = append(c.history, result)
    return result
}

func (c *Calculator[T]) GetHistory() []T {
    return c.history
}

func (c *Calculator[T]) Average() T {
    if len(c.history) == 0 {
        var zero T
        return zero
    }
    
    var sum T
    for _, value := range c.history {
        sum += value
    }
    
    return sum / T(len(c.history))
}

// 7. 类型别名和泛型
type StringMap[V any] map[string]V
type IntSlice[T Integer] []T

func (sm StringMap[V]) Get(key string) (V, bool) {
    value, exists := sm[key]
    return value, exists
}

func (sm StringMap[V]) Set(key string, value V) {
    sm[key] = value
}

func (is IntSlice[T]) Sum() T {
    var sum T
    for _, value := range is {
        sum += value
    }
    return sum
}

func main() {
    // 1. 类型推断
    TypeInference()
    
    // 2. 方法约束
    fmt.Println("\n=== 方法约束 ===")
    
    people := []Person{
        {"Alice", 30},
        {"Bob", 25},
        {"Charlie", 35},
        {"Diana", 28},
    }
    
    fmt.Printf("排序前: %v\n", people)
    Sort(people)
    fmt.Printf("排序后: %v\n", people)
    
    // 3. 泛型集合
    fmt.Println("\n=== 泛型集合 ===")
    
    intSet := NewSet[int]()
    intSet.Add(1)
    intSet.Add(2)
    intSet.Add(3)
    intSet.Add(2) // 重复元素
    
    fmt.Printf("集合大小: %d\n", intSet.Size())
    fmt.Printf("包含2: %t\n", intSet.Contains(2))
    fmt.Printf("集合内容: %v\n", intSet.ToSlice())
    
    intSet.Remove(2)
    fmt.Printf("删除2后: %v\n", intSet.ToSlice())
    
    // 4. 高阶函数
    fmt.Println("\n=== 高阶函数 ===")
    
    numbers := []int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
    
    // 过滤偶数并转换为字符串
    evenStrings := FilterMap(numbers,
        func(n int) bool { return n%2 == 0 },
        func(n int) string { return fmt.Sprintf("even_%d", n) },
    )
    
    fmt.Printf("偶数字符串: %v\n", evenStrings)
    
    // 5. 泛型计算器
    fmt.Println("\n=== 泛型计算器 ===")
    
    intCalc := NewCalculator[int]()
    intCalc.Add(10, 20)
    intCalc.Multiply(5, 6)
    intCalc.Add(15, 25)
    
    fmt.Printf("整数计算历史: %v\n", intCalc.GetHistory())
    fmt.Printf("平均值: %d\n", intCalc.Average())
    
    floatCalc := NewCalculator[float64]()
    floatCalc.Add(3.14, 2.86)
    floatCalc.Multiply(2.5, 4.0)
    
    fmt.Printf("浮点计算历史: %v\n", floatCalc.GetHistory())
    fmt.Printf("平均值: %.2f\n", floatCalc.Average())
    
    // 6. 类型别名
    fmt.Println("\n=== 类型别名 ===")
    
    userMap := make(StringMap[string])
    userMap.Set("user1", "Alice")
    userMap.Set("user2", "Bob")
    
    if name, exists := userMap.Get("user1"); exists {
        fmt.Printf("用户1: %s\n", name)
    }
    
    intSlice := IntSlice[int]{1, 2, 3, 4, 5}
    fmt.Printf("整数切片和: %d\n", intSlice.Sum())
    
    // 7. 反射和泛型
    fmt.Println("\n=== 反射和泛型 ===")
    
    printTypeInfo := func[T any](value T) {
        fmt.Printf("值: %v, 类型: %T, 反射类型: %v\n", 
            value, value, reflect.TypeOf(value))
    }
    
    printTypeInfo(42)
    printTypeInfo("hello")
    printTypeInfo(3.14)
    printTypeInfo([]int{1, 2, 3})
}

总结

  1. 泛型基础

    • 使用[T any]定义类型参数
    • anyinterface{}的别名
    • 支持多个类型参数
    • 编译时类型检查
  2. 类型约束

    • constraints.Ordered:可排序类型
    • comparable:可比较类型
    • 自定义约束接口
    • 类型联合:int | float64
  3. 泛型类型

    • 泛型结构体:type Stack[T any] struct
    • 泛型接口:type Container[T any] interface
    • 泛型方法:在泛型类型上定义方法
    • 类型别名:type StringMap[V any] map[string]V
  4. 高级特性

    • 类型推断:编译器自动推断类型参数
    • 方法约束:约束必须实现特定方法
    • 高阶函数:函数作为类型参数
    • 嵌套泛型:泛型类型作为其他泛型的参数
  5. 最佳实践

    • 优先使用标准约束(如constraints.Ordered
    • 避免过度使用泛型
    • 合理命名类型参数(T, K, V等)
    • 在需要类型安全和代码重用时使用泛型
    • 注意泛型的编译时开销
updatedupdated2025-09-202025-09-20