File tree Expand file tree Collapse file tree 2 files changed +67
-0
lines changed
Expand file tree Collapse file tree 2 files changed +67
-0
lines changed Original file line number Diff line number Diff line change 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+ }
Original file line number Diff line number Diff line change 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+ }
You can’t perform that action at this time.
0 commit comments