go-learning/tour_of_go/l6/generics.go

37 lines
634 B
Go
Raw Permalink Normal View History

2025-09-26 14:43:54 +00:00
package main
import (
"fmt"
)
type List[T any] struct {
next *List[T]
val T
}
func (l *List[T]) Prepend(v T) *List[T] {
return &List[T]{next: l, val: v}
}
func (l *List[t]) Len() int {
count := 0
for cur := l; cur != nil; cur = cur.next {
count++
}
return count
}
func main() {
var test_list *List[int]
fmt.Println(test_list)
test_list = test_list.Prepend(10)
fmt.Println(test_list)
test_list = test_list.Prepend(20)
fmt.Println(test_list)
fmt.Printf("The list has %d items\n", test_list.Len())
test_list = test_list.Prepend(30)
fmt.Println(test_list)
fmt.Printf("The list has %d items", test_list.Len())
}