Generic types
练习题目:
In addition to generic functions, Go also supports generic types. A type can be parameterized with a type parameter, which could be useful for implementing generic data structures.
This example demonstrates a simple type declaration for a singly-linked list holding any type of value.
As an exercise, add some functionality to this list implementation.
练习程序:
package main
import "fmt"
// List represents a singly-linked list that holds
// values of any type.
type List[T any] struct {
next *List[T]
val T
}
func AddList[T any](x T) List[T] {
i := List[T]{}
i.next = &i
i.val = x
return i
}
func main() {
a := List[int]{}
a.val = 1
list := AddList(123)
a.next = &list
fmt.Println("New list is", list.next, list.val)
b := List[string]{}
b.val = "123"
blist := AddList("456")
b.next = &blist
fmt.Println("New list is", blist.next, blist.val)
}
运行结果:
New list is &{0xc000108050 123} 123
New list is &{0xc000114000 456} 456
学习笔记:该联系目的在于掌握GO语言中的泛型类型,通过定了一个可设置任意类型的Struct结构体List,实现了一个单向链表,并通过AddList函数向链表中加入链表节点。在main函数运行中,可以定义int类型的链表,也可以定义string类型的链表。