Add generics

This commit is contained in:
Sangeeth Sudheer 2024-04-27 11:37:29 +05:30
parent 867a7687e7
commit 4bc7680ff7
Signed by: x
GPG Key ID: F6D06ECE734C57D1
2 changed files with 67 additions and 2 deletions

63
generics/generics.go Normal file
View File

@ -0,0 +1,63 @@
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)
}

View File

@ -1,9 +1,11 @@
package main package main
// import "git.sangeeth.dev/gobyexample/runes" // import "git.sangeeth.dev/gobyexample/runes"
import "git.sangeeth.dev/gobyexample/structs" // import "git.sangeeth.dev/gobyexample/structs"
import "git.sangeeth.dev/gobyexample/generics"
func main() { func main() {
// runes.Runes() // runes.Runes()
structs.Structs() // structs.Structs()
generics.Generics()
} }