From bb139508fc3c9c154b2cc836f677ac07e1ce88fc Mon Sep 17 00:00:00 2001 From: Jason Song Date: Tue, 24 Oct 2023 17:28:56 +0800 Subject: [PATCH] feat: support V --- generic.go | 10 ++++++- generic_test.go | 80 +++++++++++++++++++++++++++++-------------------- 2 files changed, 56 insertions(+), 34 deletions(-) diff --git a/generic.go b/generic.go index fc369fa..889d6ef 100644 --- a/generic.go +++ b/generic.go @@ -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 +} diff --git a/generic_test.go b/generic_test.go index e56e25b..c756d3a 100644 --- a/generic_test.go +++ b/generic_test.go @@ -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, "") + } + }) }