https://go.dev/tour/generics/2
코드를 입력하세요package main
import (
"fmt"
)
type List[T any] struct {
next *List[T]
val T
}
func (l *List[T]) Add(item T) *List[T] {
newNode := &List[T]{val: item}
if l == nil {
return newNode
}
current := l
for current.next != nil {
current = current.next
}
current.next = newNode
return l
}
func (l *List[T]) Print() {
current := l
for current != nil {
fmt.Println(current.val)
current = current.next
}
}
func main() {
var intList *List[int]
intList = intList.Add(1)
intList = intList.Add(2)
intList = intList.Add(3)
fmt.Println("Int list:")
intList.Print()
var stringList *List[string]
stringList = stringList.Add("A")
stringList = stringList.Add("B")
stringList = stringList.Add("C")
fmt.Println("String list:")
stringList.Print()
}