diff --git a/convertor/convertor.go b/convertor/convertor.go index ea53b22..ecc7d98 100644 --- a/convertor/convertor.go +++ b/convertor/convertor.go @@ -170,6 +170,11 @@ func ToInt(value any) (int64, error) { } } +// ToPointer returns a pointer to this value +func ToPointer[T any](value T) *T { + return &value +} + // StructToMap convert struct to map, only convert exported struct field // map key is specified same as struct field tag `json` value func StructToMap(value any) (map[string]any, error) { diff --git a/convertor/convertor_test.go b/convertor/convertor_test.go index 69c597a..a83704b 100644 --- a/convertor/convertor_test.go +++ b/convertor/convertor_test.go @@ -178,3 +178,10 @@ func TestColorRGBToHex(t *testing.T) { assert := internal.NewAssert(t, "TestColorRGBToHex") assert.Equal(expected, colorHex) } + +func TestToPointer(t *testing.T) { + assert := internal.NewAssert(t, "TestToPointer") + result := ToPointer[int](123) + + assert.Equal(*result, 123) +} diff --git a/slice/slice.go b/slice/slice.go index d548851..6ab2976 100644 --- a/slice/slice.go +++ b/slice/slice.go @@ -803,3 +803,21 @@ func LastIndexOf[T any](slice []T, value T) int { return -1 } + +// ToSlicePointer returns a pointer to the slices of a variable parameter transformation +func ToSlicePointer[T any](value ...T) []*T { + out := make([]*T, len(value)) + for i := range value { + out[i] = &value[i] + } + return out +} + +// ToSlice returns a slices of a variable parameter transformation +func ToSlice[T any](value ...T) []T { + out := make([]T, len(value)) + for i := range value { + out[i] = value[i] + } + return out +} diff --git a/slice/slice_test.go b/slice/slice_test.go index 1d8b2cf..60eed77 100644 --- a/slice/slice_test.go +++ b/slice/slice_test.go @@ -583,3 +583,21 @@ func TestLastIndexOf(t *testing.T) { assert.Equal(1, LastIndexOf(arr, "a")) assert.Equal(-1, LastIndexOf(arr, "d")) } + +func TestToSlice(t *testing.T) { + assert := internal.NewAssert(t, "TestToSlice") + + str1 := "a" + str2 := "b" + assert.Equal([]string{"a"}, ToSlice(str1)) + assert.Equal([]string{"a", "b"}, ToSlice(str1, str2)) +} + +func TestToSlicePointer(t *testing.T) { + assert := internal.NewAssert(t, "TestToSlicePointer") + + str1 := "a" + str2 := "b" + assert.Equal([]*string{&str1}, ToSlicePointer(str1)) + assert.Equal([]*string{&str1, &str2}, ToSlicePointer(str1, str2)) +}