From c611a0f951eebb7c0820d15e16f2c75f98d9f9ed Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?KevinZ=C3=B8nda?= <33132228+KevinZonda@users.noreply.github.com> Date: Tue, 11 Apr 2023 22:46:29 +0100 Subject: [PATCH] more --- pkg/arrayx/idx.go | 8 ++++++++ pkg/{maps => mapx}/clone.go | 2 +- pkg/stringx/cast.go | 7 +++++++ 3 files changed, 16 insertions(+), 1 deletion(-) create mode 100644 pkg/arrayx/idx.go rename pkg/{maps => mapx}/clone.go (98%) diff --git a/pkg/arrayx/idx.go b/pkg/arrayx/idx.go new file mode 100644 index 0000000..24cff46 --- /dev/null +++ b/pkg/arrayx/idx.go @@ -0,0 +1,8 @@ +package arrayx + +func SafeIndex[T any](s []T, i int, ifFailed T) T { + if i < 0 || i >= len(s) { + return ifFailed + } + return s[i] +} diff --git a/pkg/maps/clone.go b/pkg/mapx/clone.go similarity index 98% rename from pkg/maps/clone.go rename to pkg/mapx/clone.go index 74e1193..aaa5fe1 100644 --- a/pkg/maps/clone.go +++ b/pkg/mapx/clone.go @@ -1,4 +1,4 @@ -package maps +package mapx func Clone[K comparable, V any](m map[K]V) map[K]V { newM := make(map[K]V, len(m)) diff --git a/pkg/stringx/cast.go b/pkg/stringx/cast.go index c526e80..b681f63 100644 --- a/pkg/stringx/cast.go +++ b/pkg/stringx/cast.go @@ -25,3 +25,10 @@ func Bool(s string) (bool, error) { func Ptr(s string) *string { return &s } + +func AutoPtr(s string) *string { + if s == "" { + return nil + } + return &s +}