Skip to content

Commit

Permalink
Add test
Browse files Browse the repository at this point in the history
  • Loading branch information
AlekSi committed Oct 15, 2021
1 parent 47b3772 commit a285f58
Show file tree
Hide file tree
Showing 3 changed files with 38 additions and 2 deletions.
5 changes: 4 additions & 1 deletion generic.go
Original file line number Diff line number Diff line change
@@ -1,11 +1,14 @@
//go:build go1.18
// +build go1.18

package pointer

func To[T any](t T) *T {
return &t
}

func ToOrNil[T comparable](t T) *T {
if z, ok := interface{}(t).(interface{ IsZero() bool }); ok {
if z, ok := any(t).(interface{ IsZero() bool }); ok {
if z.IsZero() {
return nil
}
Expand Down
33 changes: 33 additions & 0 deletions generic_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
//go:build go1.18
// +build go1.18

package pointer

import (
"testing"
"time"
)

func TestGeneric(t *testing.T) {
var x time.Time
if *To(x) != x {
t.Errorf("*To(%v)", x)
}
if ToOrNil(x) != nil {
t.Errorf("ToOrNil(%v)", x)
}
if Get((*time.Time)(nil)) != x {
t.Errorf("Time(%v)", nil)
}

x = time.Date(2014, 6, 25, 12, 24, 40, 0, time.UTC)
if *To(x) != x {
t.Errorf("*To(%v)", x)
}
if *ToOrNil(x) != x {
t.Errorf("*ToOrNil(%v)", x)
}
if Get(&x) != x {
t.Errorf("Get(%v)", &x)
}
}
2 changes: 1 addition & 1 deletion go.mod
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
module github.com/AlekSi/pointer

go 1.11
go 1.18

0 comments on commit a285f58

Please sign in to comment.