1
2
3
4
5
6
7 package main
8
9 import (
10 "fmt"
11 "reflect"
12 "strconv"
13 )
14
15
16
17 func mapper[F, T any](s []F, f func(F) T) []T {
18 r := make([]T, len(s))
19 for i, v := range s {
20 r[i] = f(v)
21 }
22 return r
23 }
24
25 func main() {
26 got := mapper([]int{1, 2, 3}, strconv.Itoa)
27 want := []string{"1", "2", "3"}
28 if !reflect.DeepEqual(got, want) {
29 panic(fmt.Sprintf("got %s, want %s", got, want))
30 }
31
32 fgot := mapper([]float64{2.5, 2.3, 3.5}, func(f float64) string {
33 return strconv.FormatFloat(f, 'f', -1, 64)
34 })
35 fwant := []string{"2.5", "2.3", "3.5"}
36 if !reflect.DeepEqual(fgot, fwant) {
37 panic(fmt.Sprintf("got %s, want %s", fgot, fwant))
38 }
39 }
40
View as plain text