forked from steger/pr3-ws202526
generics
parent
c11ff4321e
commit
0872d4f39d
|
|
@ -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())
|
||||
}
|
||||
|
|
|
|||
Loading…
Reference in New Issue