Add generics
This commit is contained in:
parent
867a7687e7
commit
4bc7680ff7
63
generics/generics.go
Normal file
63
generics/generics.go
Normal 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)
|
||||
}
|
6
main.go
6
main.go
@ -1,9 +1,11 @@
|
||||
package main
|
||||
|
||||
// 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() {
|
||||
// runes.Runes()
|
||||
structs.Structs()
|
||||
// structs.Structs()
|
||||
generics.Generics()
|
||||
}
|
||||
|
Loading…
Reference in New Issue
Block a user