Skip to content

Commit

Permalink
feat: support V
Browse files Browse the repository at this point in the history
  • Loading branch information
wolfogre committed Oct 24, 2023
1 parent a743078 commit bb13950
Show file tree
Hide file tree
Showing 2 changed files with 56 additions and 34 deletions.
10 changes: 9 additions & 1 deletion generic.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,14 @@
package pt

// P return pointer of v
func P[V any](v V) *V {
func P[T any](v T) *T {
return &v
}

// V return value of p
func V[T any](p *T) T {
if p == nil {
return *new(T)
}
return *p
}
80 changes: 47 additions & 33 deletions generic_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,37 +10,51 @@ import (
)

func TestP(t *testing.T) {
type args struct {
v any
}
tests := []struct {
name string
args args
}{
{
name: "int",
args: args{
v: 1,
},
},
{
name: "float64",
args: args{
v: 1.1,
},
},
{
name: "time",
args: args{
v: time.Now(),
},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if got := pt.P(tt.args.v); *got != tt.args.v {
t.Errorf("P() = %v, want %v", got, tt.args.v)
}
})
}
t.Run("int", func(t *testing.T) {
if got := pt.P(1); *got != 1 {
t.Errorf("P() = %v, want %v", *got, 1)
}
})
t.Run("float64", func(t *testing.T) {
if got := pt.P(1.1); *got != 1.1 {
t.Errorf("P() = %v, want %v", *got, 1)
}
})
t.Run("time", func(t *testing.T) {
now := time.Now()
if got := pt.P(now); *got != now {
t.Errorf("P() = %v, want %v", *got, 1)
}
})
}

func TestV(t *testing.T) {
t.Run("int", func(t *testing.T) {
if got := pt.V(pt.P(1)); got != 1 {
t.Errorf("V() = %v, want %v", got, 1)
}
})
t.Run("float64", func(t *testing.T) {
if got := pt.V(pt.P(1.1)); got != 1.1 {
t.Errorf("V() = %v, want %v", got, 1)
}
})
t.Run("time", func(t *testing.T) {
now := time.Now()
if got := pt.V(pt.P(now)); got != now {
t.Errorf("V() = %v, want %v", got, 1)
}
})
t.Run("nil int", func(t *testing.T) {
var i *int
if got := pt.V(i); got != 0 {
t.Errorf("V() = %v, want %v", got, 0)
}
})
t.Run("nil string", func(t *testing.T) {
var s *string
if got := pt.V(s); got != "" {
t.Errorf("V() = %v, want %v", got, "")
}
})
}

0 comments on commit bb13950

Please sign in to comment.