adding support for quick pointer conversion (#38)

* adding support for quick pointer convertion

* function comment update
This commit is contained in:
Carlos A Saavedra 2024-11-01 04:24:53 -05:00 committed by GitHub
parent acf26bbaf9
commit fbbd0398c9
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
2 changed files with 67 additions and 0 deletions

22
pointers.go Normal file
View file

@ -0,0 +1,22 @@
package underscore
// Convert values to pointers
//
// Instead of:
// v := "value"
// MyPointerVar = &v
//
// Or
// v1 := "value1"
// v2 := 100
//
// obj := Obj{
// Field1: &v,
// Field2: &v2,
// }
//
// Use:
// MyPointerVar = ToPointer("value")
func ToPointer[T any](in T) *T {
return &in
}

45
pointers_test.go Normal file
View file

@ -0,0 +1,45 @@
package underscore_test
import (
"reflect"
"testing"
u "github.com/rjNemo/underscore"
"github.com/stretchr/testify/assert"
)
func TestPointers(t *testing.T) {
variable := 123
var object struct{}
cases := []struct {
value any
expected bool
}{
{
value: u.ToPointer("myValue"),
expected: true,
},
{
value: u.ToPointer(variable),
expected: true,
},
{
value: &variable,
expected: true,
},
{
value: nil,
expected: false,
},
{
value: u.ToPointer(object),
expected: true,
},
}
for _, c := range cases {
got := (reflect.ValueOf(c.value).Kind() == reflect.Ptr)
assert.Equal(t, c.expected, got)
}
}