| 1 |
// Copyright (c) 2024 Tulir Asokan |
| 2 |
// |
| 3 |
// This Source Code Form is subject to the terms of the Mozilla Public |
| 4 |
// License, v. 2.0. If a copy of the MPL was not distributed with this |
| 5 |
// file, You can obtain one at http://mozilla.org/MPL/2.0/. |
| 6 |
|
| 7 |
package exslices |
| 8 |
|
| 9 |
func CastFunc[To, From any](source []From, conv func(From) To) []To { |
| 10 |
result := make([]To, len(source)) |
| 11 |
for i, v := range source { |
| 12 |
result[i] = conv(v) |
| 13 |
} |
| 14 |
return result |
| 15 |
} |
| 16 |
|
| 17 |
func CastFuncFilter[To, From any](source []From, conv func(From) (To, bool)) []To { |
| 18 |
result := make([]To, 0, len(source)) |
| 19 |
for _, v := range source { |
| 20 |
res, ok := conv(v) |
| 21 |
if ok { |
| 22 |
result = append(result, res) |
| 23 |
} |
| 24 |
} |
| 25 |
return result |
| 26 |
} |
| 27 |
|
| 28 |
func CastToString[To, From ~string](source []From) []To { |
| 29 |
result := make([]To, len(source)) |
| 30 |
for i, v := range source { |
| 31 |
result[i] = To(v) |
| 32 |
} |
| 33 |
return result |
| 34 |
} |
| 35 |
|
| 36 |
func CastToAny[From any](source []From) []any { |
| 37 |
result := make([]any, len(source)) |
| 38 |
for i, v := range source { |
| 39 |
result[i] = v |
| 40 |
} |
| 41 |
return result |
| 42 |
} |