gobyexample/generics/generics.go

64 lines
870 B
Go
Raw Normal View History

2024-04-27 06:07:29 +00:00
package generics
import (
"fmt"
"io"
"os"
)
type LinkedList[T any] struct {
Head *LinkedListElement[T]
Tail *LinkedListElement[T]
}
type LinkedListElement[T any] struct {
Next *LinkedListElement[T]
Value T
}
func NewLinkedList[T any]() *LinkedList[T] {
return &LinkedList[T]{}
}
func (lst *LinkedList[T]) Push(value T) *LinkedListElement[T] {
node := &LinkedListElement[T]{
Value: value,
}
if lst.Head == nil {
lst.Head = node
lst.Tail = node
}
lst.Tail.Next = node
lst.Tail = lst.Tail.Next
return lst.Tail
}
func (lst *LinkedList[T]) Print(out io.Writer) {
curr := lst.Head
for curr != nil {
fmt.Fprint(out, curr.Value)
if curr.Next != nil {
fmt.Fprint(out, " → ")
}
curr = curr.Next
}
fmt.Fprintln(out)
}
func Generics() {
lst := NewLinkedList[int]()
for i := range 5 {
lst.Push(i)
}
lst.Print(os.Stdout)
}