Add EmptyableToPtr (#311)

* Add EmptyableToPtr
This commit is contained in:
Oganes Mirzoyan
2023-03-20 20:05:30 +03:00
committed by GitHub
parent 9ec076e4f6
commit 56f34e0891
3 changed files with 51 additions and 0 deletions

View File

@@ -1,10 +1,23 @@
package lo
import "reflect"
// ToPtr returns a pointer copy of value.
func ToPtr[T any](x T) *T {
return &x
}
// EmptyableToPtr returns a pointer copy of value if it's nonzero.
// Otherwise, returns nil pointer.
func EmptyableToPtr[T any](x T) *T {
isZero := reflect.ValueOf(&x).Elem().IsZero()
if isZero {
return nil
}
return &x
}
// FromPtr returns the pointer value or empty.
func FromPtr[T any](x *T) T {
if x == nil {