From 0872d4f39db24ec7151f852286c69f52e11561a3 Mon Sep 17 00:00:00 2001 From: Sebastian Steger Date: Wed, 20 Aug 2025 07:04:27 +0000 Subject: [PATCH] generics --- go/02-next-level/05-generics.go | 31 ++++++++++++++++++------------- 1 file changed, 18 insertions(+), 13 deletions(-) diff --git a/go/02-next-level/05-generics.go b/go/02-next-level/05-generics.go index 5481cb1..09fe044 100644 --- a/go/02-next-level/05-generics.go +++ b/go/02-next-level/05-generics.go @@ -2,7 +2,7 @@ package main import "fmt" -func SlicesIndex[S []E, E int](s []string, v string) int { +func SlicesIndex[S []E, E comparable](s S, v E) int { for i := range s { if v == s[i] { return i @@ -11,27 +11,27 @@ func SlicesIndex[S []E, E int](s []string, v string) int { return -1 } -type List struct { - head, tail *element +type List[T any] struct { + head, tail *element[T] } -type element struct { - next *element - val int +type element[T any] struct { + next *element[T] + val T } -func (lst *List) Push(v int) { +func (lst *List[T]) Push(v T) { if lst.tail == nil { - lst.head = &element{val: v} + lst.head = &element[T]{val: v} lst.tail = lst.head } else { - lst.tail.next = &element{val: v} + lst.tail.next = &element[T]{val: v} lst.tail = lst.tail.next } } -func (lst *List) AllElements() []int { - var elems []int +func (lst *List[T]) AllElements() []T { + var elems []T for e := lst.head; e != nil; e = e.next { elems = append(elems, e.val) } @@ -40,12 +40,17 @@ func (lst *List) AllElements() []int { func main() { var s = []string{"foo", "bar", "zoo"} - fmt.Println("index of zoo:", SlicesIndex(s, "zoo")) - lst := List{} + _ = SlicesIndex[[]string, string](s, "zoo") + + var s2 = []int{2, 4, 5, 6} + fmt.Println("index of 4: ", SlicesIndex(s2, 4)) + + lst := List[float64]{} lst.Push(10) lst.Push(13) lst.Push(23) + lst.Push(23.3) fmt.Println("list:", lst.AllElements()) }