Skip to content
This repository has been archived by the owner on Aug 12, 2022. It is now read-only.

feat: Add ToPointer helper function to convert values to pointers #427

Merged
merged 1 commit into from
Jul 21, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 20 additions & 0 deletions helpers/pointers.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
package helpers

import "reflect"

// ToPointer takes an interface{} object and will return a pointer to this object
// if the object is not already a pointer. Otherwise, it will return the original value.
// It is safe to typecast the return-value of GetPointer into a pointer of the right type,
// except in very special cases (such as passing in nil without an explicit type)
func ToPointer(v interface{}) interface{} {
val := reflect.ValueOf(v)
if val.Kind() == reflect.Ptr {
return v
}
if !val.IsValid() {
return v
}
p := reflect.New(val.Type())
p.Elem().Set(val)
return p.Interface()
}
50 changes: 50 additions & 0 deletions helpers/pointers_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
package helpers

import (
"testing"
)

type testStruct struct {
test string
}

func TestToPointer(t *testing.T) {
// passing string should return pointer to string
give := "test"
got := ToPointer(give)
if _, ok := got.(*string); !ok {
t.Errorf("ToPointer(%q) returned %q, expected type *string", give, got)
}

// passing struct by value should return pointer to (copy of the) struct
giveObj := testStruct{
test: "value",
}
gotStruct := ToPointer(giveObj)
if _, ok := gotStruct.(*testStruct); !ok {
t.Errorf("ToPointer(%q) returned %q, expected type *testStruct", giveObj, gotStruct)
}

// passing pointer should return the original pointer
ptr := &giveObj
gotPointer := ToPointer(ptr)
if gotPointer != ptr {
t.Errorf("ToPointer(%q) returned %q, expected %q", ptr, gotPointer, ptr)
}

// passing nil should return nil back without panicking
gotNil := ToPointer(nil)
if gotNil != nil {
t.Errorf("ToPointer(%v) returned %q, expected nil", nil, gotNil)
}

// passing number should return pointer to number
giveNumber := int64(0)
gotNumber := ToPointer(giveNumber)
if v, ok := gotNumber.(*int64); !ok {
t.Errorf("ToPointer(%q) returned %q, expected type *int64", giveNumber, gotNumber)
if *v != 0 {
t.Errorf("ToPointer(%q) returned %q, expected 0", giveNumber, gotNumber)
}
}
}