| 1 |
// run |
| 2 |
|
| 3 |
// Copyright 2021 The Go Authors. All rights reserved. |
| 4 |
// Use of this source code is governed by a BSD-style |
| 5 |
// license that can be found in the LICENSE file. |
| 6 |
|
| 7 |
package main |
| 8 |
|
| 9 |
import ( |
| 10 |
"fmt" |
| 11 |
"reflect" |
| 12 |
"strconv" |
| 13 |
) |
| 14 |
|
| 15 |
// Map calls the function f on every element of the slice s, |
| 16 |
// returning a new slice of the results. |
| 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 |
} |