Skip to content

Commit fbbd039

Browse files
authored
adding support for quick pointer conversion (#38)
* adding support for quick pointer convertion * function comment update
1 parent acf26bb commit fbbd039

File tree

2 files changed

+67
-0
lines changed

2 files changed

+67
-0
lines changed

pointers.go

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
package underscore
2+
3+
// Convert values to pointers
4+
//
5+
// Instead of:
6+
// v := "value"
7+
// MyPointerVar = &v
8+
//
9+
// Or
10+
// v1 := "value1"
11+
// v2 := 100
12+
//
13+
// obj := Obj{
14+
// Field1: &v,
15+
// Field2: &v2,
16+
// }
17+
//
18+
// Use:
19+
// MyPointerVar = ToPointer("value")
20+
func ToPointer[T any](in T) *T {
21+
return &in
22+
}

pointers_test.go

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
package underscore_test
2+
3+
import (
4+
"reflect"
5+
"testing"
6+
7+
u "github.com/rjNemo/underscore"
8+
"github.com/stretchr/testify/assert"
9+
)
10+
11+
func TestPointers(t *testing.T) {
12+
variable := 123
13+
var object struct{}
14+
15+
cases := []struct {
16+
value any
17+
expected bool
18+
}{
19+
{
20+
value: u.ToPointer("myValue"),
21+
expected: true,
22+
},
23+
{
24+
value: u.ToPointer(variable),
25+
expected: true,
26+
},
27+
{
28+
value: &variable,
29+
expected: true,
30+
},
31+
{
32+
value: nil,
33+
expected: false,
34+
},
35+
{
36+
value: u.ToPointer(object),
37+
expected: true,
38+
},
39+
}
40+
41+
for _, c := range cases {
42+
got := (reflect.ValueOf(c.value).Kind() == reflect.Ptr)
43+
assert.Equal(t, c.expected, got)
44+
}
45+
}

0 commit comments

Comments
 (0)