Go 泛型与接口反射的深入解析
1. Go 泛型在结构体中的应用
泛型在 Go 语言中是一项强大的特性,它能让代码更具灵活性,可处理多种数据类型。下面我们通过实现一个通用的链表来详细了解泛型在结构体中的应用。
package main
import (
"fmt"
)
type node[T any] struct {
Data T
next *node[T]
}
type list[T any] struct {
start *node[T]
}
func (l *list[T]) add(data T) {
n := node[T]{
Data: data,
next: nil,
}
if l.start == nil {
l.start = &n
return
}
if l.start.next == nil {
l.start.next = &n
return
}
temp := l.start
l.start = l.start.next
l.add(data)
l.start = temp
}
func main() {
var myList list[int]
fmt.Println(myList)
myList.add(12)
myList.add(9)
myList.add(3)
myList.add(9)
cur := myList.start
超级会员免费看
订阅专栏 解锁全文
63

被折叠的 条评论
为什么被折叠?



