mirror of
https://github.com/rjNemo/underscore
synced 2026-06-06 02:26:42 +00:00
adding support for quick pointer conversion (#38)
* adding support for quick pointer convertion * function comment update
This commit is contained in:
parent
acf26bbaf9
commit
fbbd0398c9
2 changed files with 67 additions and 0 deletions
22
pointers.go
Normal file
22
pointers.go
Normal 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
45
pointers_test.go
Normal 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)
|
||||||
|
}
|
||||||
|
}
|
||||||
Loading…
Reference in a new issue