From 8eb5f983dca1a13547f4fcc4064201d8e2f6bb75 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..d05a9a42 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) + + nilFloat64 := Nil[float64]() + var expNilFloat64 *float64 + + nilString := Nil[string]() + var expNilString *string + + is.Equal(expNilFloat64, nilFloat64) + is.Nil(nilFloat64) + is.NotEqual(nil, nilFloat64) + + is.Equal(expNilString, nilString) + is.Nil(nilString) + is.NotEqual(nil, nilString) + + is.NotEqual(nilString, nilFloat64) +} + func TestEmptyableToPtr(t *testing.T) { t.Parallel() is := assert.New(t)