泛型
package main
import ( "cmp" "fmt")
func Max[T cmp.Ordered](a, b T) T { if a > b { return a } return b}
func PrintSlice[T any](s []T) { for _, v := range s { fmt.Println(v, " ") } fmt.Println()}
func FindIndex[T comparable](slice []T, target T) int { for i, v := range slice { if v == target { return i } } return -1}
type Stringer interface { String() string}
func PrintAll[T Stringer](items []T) { for _, item := range items { fmt.Println(item.String()) }}
type Person struct { Name string}
func (p Person) String() string { return fmt.Sprintf("Name: %s", p.Name)}
func main() { intSlice := []int{1, 2, 3, 4, 5} PrintSlice(intSlice) fmt.Println(FindIndex(intSlice, 3)) // 2
strSlice := []string{"a", "b", "c", "d", "e"} PrintSlice(strSlice) fmt.Println(FindIndex(strSlice, "c")) // 2
fmt.Println(Max(1, 2)) // 2 fmt.Println(Max(1.1, 1.2)) // 1.2
ps := []Person{ {"Tom"}, {"Jerry"}, } PrintAll(ps)}package main
import "fmt"
func Map[T, U any](slice []T, f func(T) U) []U { result := make([]U, len(slice)) for i, v := range slice { result[i] = f(v) } return result}
func Filter[T any](slice []T, f func(T) bool) []T { var result []T for _, v := range slice { if f(v) { result = append(result, v) } } return result}
type Pair[K comparable, V any] struct { Key K Value V}
func main() { numbers := []int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10} squares := Map(numbers, func(n int) int { return n * n }) fmt.Println(squares) // [1 4 9 16 25 36 49 64 81 100]
p1 := Pair[string, int]{"one", 1} p2 := Pair[int, string]{100, "hello"} fmt.Println(p1, p2) // {one 1} {two 2}}