Generics
package main
import "fmt"
// MapKeys is a generic function that takes a map and returns a slice containing all keys of the map.
func MapKeys[K comparable, V any](m map[K]V) []K {
r := make([]K, 0, len(m))
for k := range m {
r = append(r, k)
}
return r
}
// List is a generic linked list with elements of type T.
type List[T any] struct {
head, tail *element[T]
}
// element is a generic element in the linked list.
type element[T any] struct {
next *element[T]
val T
}
// Push adds a new element to the end of the list.
func (lst *List[T]) Push(v T) {
if lst.tail == nil {
lst.head = &element[T]{val: v}
lst.tail = lst.head
} else {
lst.tail.next = &element[T]{val: v}
lst.tail = lst.tail.next
}
}
// GetAll returns all elements in the list as a slice.
func (lst *List[T]) GetAll() []T {
var elems []T
for e := lst.head; e != nil; e = e.next {
elems = append(elems, e.val)
}
return elems
}
func main() {
// Create a map with integer keys and string values
var m = map[int]string{1: "2", 2: "4", 4: "8"}
// Call the MapKeys function to retrieve all keys of the map and print them
fmt.Println("keys:", MapKeys(m))
// Another way to call MapKeys with explicit types
_ = MapKeys[int, string](m)
// Create a generic linked list of integers
lst := List[int]{}
lst.Push(10)
lst.Push(13)
lst.Push(23)
// Retrieve all elements from the list and print them
fmt.Println("list:", lst.GetAll())
}Output
Last updated