From a29c13534bbe75f51a45e7de0de1ed0062b53bb5 Mon Sep 17 00:00:00 2001 From: Gustavo Okuyama Date: Thu, 5 Oct 2023 18:09:01 -0300 Subject: [PATCH] feat(type_manipulation): add Nil --- README.md | 10 ++++++++++ type_manipulation.go | 5 +++++ type_manipulation_test.go | 21 +++++++++++++++++++++ 3 files changed, 36 insertions(+) diff --git a/README.md b/README.md index eddbdecb..78bcbc39 100644 --- a/README.md +++ b/README.md @@ -217,6 +217,7 @@ Conditional helpers: Type manipulation helpers: - [ToPtr](#toptr) +- [Nil](#nil) - [EmptyableToPtr](#emptyabletoptr) - [FromPtr](#fromptr) - [FromPtrOr](#fromptror) @@ -2164,6 +2165,15 @@ ptr := lo.ToPtr("hello world") // *string{"hello world"} ``` +### Nil + +Returns a nil pointer of type. + +```go +ptr := lo.Nil[float64]() +// nil +``` + ### EmptyableToPtr Returns a pointer copy of value if it's nonzero. diff --git a/type_manipulation.go b/type_manipulation.go index 45d8fe20..09ca40e1 100644 --- a/type_manipulation.go +++ b/type_manipulation.go @@ -7,6 +7,11 @@ func ToPtr[T any](x T) *T { return &x } +// Nil returns a nil pointer of type. +func Nil[T any]() *T { + return nil +} + // EmptyableToPtr returns a pointer copy of value if it's nonzero. // Otherwise, returns nil pointer. func EmptyableToPtr[T any](x T) *T { diff --git a/type_manipulation_test.go b/type_manipulation_test.go index 48e3676f..7da99501 100644 --- a/type_manipulation_test.go +++ b/type_manipulation_test.go @@ -15,6 +15,27 @@ func TestToPtr(t *testing.T) { is.Equal(*result1, []int{1, 2}) } +func TestNil(t *testing.T) { + t.Parallel() + is := assert.New(t) + + resultFloat64 := Nil[float64]() + var nilFloat64 *float64 + + resultString := Nil[string]() + var nilString *string + + is.Equal(nilFloat64, resultFloat64) + is.Nil(nilFloat64) + is.NotEqual(nil, resultFloat64) + + is.Equal(nilString, resultString) + is.Nil(nilString) + is.NotEqual(nil, resultString) + + is.NotEqual(resultString, resultFloat64) +} + func TestEmptyableToPtr(t *testing.T) { t.Parallel() is := assert.New(t)