2 回答

TA貢獻1780條經驗 獲得超4個贊
好消息,從 Go 1.18 開始,Go 現在支持泛型。
按照問題中的示例,這里是一個使用泛型的簡化 LinkedList。您可以在此處的操場上修改它。
package main
import "fmt"
type MyNode[T any] struct {
? ? next? *MyNode[T]
? ? value T
}
type MyLinkedList[T any] struct {
? ? head *MyNode[T]
? ? tail *MyNode[T]
}
func (list *MyLinkedList[T]) Add(t T) *MyLinkedList[T] {
? ? // create node
? ? node := &MyNode[T]{nil, t}
? ? // if first node in list
? ? if list.head == nil {
? ? ? ? list.head = node
? ? ? ? list.tail = node
? ? } else {
? ? ? ? list.tail.next = node
? ? ? ? list.tail = list.tail.next
? ? }
? ? return list
}
func (list *MyLinkedList[T]) AddBeforeHead(t T) *MyLinkedList[T] {
? ? node := &MyNode[T]{nil, t}
? ? if list.head != nil {
? ? ? ? node.next = list.head
? ? ? ? list.head = node
? ? } else {
? ? ? ? // make head
? ? ? ? list.head = node
? ? ? ? list.tail = node
? ? }
? ? return list
}
// display the list
func DisplayList[T any](list *MyLinkedList[T]) string {
? ? var out string = ""
? ? iter := list.head
? ? for iter != nil {
? ? ? ? out += fmt.Sprintf("%v -> ", iter.value)
? ? ? ? iter = iter.next
? ? }
? ? return out
}
func (list *MyLinkedList[T]) Display() string {
? ? return DisplayList(list)
}
// for printing node value
// you could also implement Stringer
// but this is besides the point, you can ignore
func (node *MyNode[T]) String() string {
? ? return fmt.Sprintf("<MyNode: %v>", node.value)
}
// helper func: create list from array
func CreateLinkedList[T any](arr []T) *MyLinkedList[T] {
? ? list := &MyLinkedList[T]{}
? ? for _, v := range arr {
? ? ? ? list.Add(v)
? ? }
? ? return list
}
func main() {
? ? // create a list from array of integers
? ? intArr := []int{10, 20, 30, 40, 50, 60}
? ? list1 := CreateLinkedList(intArr)
? ? // create a list from array of strings
? ? strArr := []string{"foo", "bar", "baz", "faz"}
? ? list2 := CreateLinkedList(strArr)
? ? // test inserting at the beginning
? ? list2.AddBeforeHead("hello")
? ? fmt.Println(list1.Display())
? ? fmt.Println(list2.Display())
}

TA貢獻1757條經驗 獲得超7個贊
您可以通過使用接口和運行時檢查(正如您所發現的那樣)或使用代碼生成來做到這一點。這些是您在 Go 中用于泛型編程的當前選項。Go 團隊正在努力為語言添加泛型——這是一項正在進行的工作,每個人都可以自由參與討論。一旦泛型存在,它們將提供您在這里尋求的解決方案。
至于接口與代碼生成,有你提到的性能影響。代碼生成將生成更緊湊的代碼,不需要對大多數操作進行運行時檢查;另一方面,它為項目的構建過程增加了一些復雜性。這些是在運行時解決某些事情與在編譯時預先計算事情的通常權衡。
- 2 回答
- 0 關注
- 190 瀏覽
添加回答
舉報