This commit is contained in:
Mike Schwörer 2023-04-23 14:54:23 +02:00
parent 5e295d65c5
commit 304e779470
Signed by: Mikescher
GPG Key ID: D3C7172E0A70F8CF

View File

@ -1,6 +1,8 @@
package langext package langext
import ( import (
"errors"
"fmt"
"reflect" "reflect"
) )
@ -382,6 +384,40 @@ func ArrCastToAny[T1 any](arr []T1) []any {
return r return r
} }
func ArrCastSafe[T1 any, T2 any](arr []T1) []T2 {
r := make([]T2, 0, len(arr))
for _, v := range arr {
if vcast, ok := any(v).(T2); ok {
r = append(r, vcast)
}
}
return r
}
func ArrCastErr[T1 any, T2 any](arr []T1) ([]T2, error) {
r := make([]T2, len(arr))
for i, v := range arr {
if vcast, ok := any(v).(T2); ok {
r[i] = vcast
} else {
return nil, errors.New(fmt.Sprintf("Cannot cast element %d of type %T to type %s", i, v, *new(T2)))
}
}
return r, nil
}
func ArrCastPanic[T1 any, T2 any](arr []T1) []T2 {
r := make([]T2, len(arr))
for i, v := range arr {
if vcast, ok := any(v).(T2); ok {
r[i] = vcast
} else {
panic(fmt.Sprintf("Cannot cast element %d of type %T to type %s", i, v, *new(T2)))
}
}
return r
}
func ArrConcat[T any](arr ...[]T) []T { func ArrConcat[T any](arr ...[]T) []T {
c := 0 c := 0
for _, v := range arr { for _, v := range arr {