mirror of
https://github.com/duke-git/lancet.git
synced 2026-02-07 22:22:29 +08:00
🐛 Fixing a bug. about pointer package function (#230)
update: 1. UnwarpOr 2. UnwarpOrDefault 3. ExtractPointer add: 1. UnwrapOr 2. IsNil
This commit is contained in:
@@ -11,17 +11,24 @@ import (
|
||||
// Of returns a pointer to the value `v`.
|
||||
// Play: https://go.dev/play/p/HFd70x4DrMj
|
||||
func Of[T any](v T) *T {
|
||||
if IsNil(v) {
|
||||
return nil
|
||||
}
|
||||
return &v
|
||||
}
|
||||
|
||||
// Unwrap returns the value from the pointer.
|
||||
// Play: https://go.dev/play/p/cgeu3g7cjWb
|
||||
//
|
||||
// Play: https://go.dev/play/p/cgeu3g7cjWb
|
||||
// Deprecated: Please use UnwrapOr
|
||||
func Unwrap[T any](p *T) T {
|
||||
return *p
|
||||
}
|
||||
|
||||
// UnwarpOr returns the value from the pointer or fallback if the pointer is nil.
|
||||
// Play: https://go.dev/play/p/mmNaLC38W8C
|
||||
//
|
||||
// Play: https://go.dev/play/p/mmNaLC38W8C
|
||||
// Deprecated: Please use UnwrapOr
|
||||
func UnwarpOr[T any](p *T, fallback T) T {
|
||||
if p == nil {
|
||||
return fallback
|
||||
@@ -30,7 +37,9 @@ func UnwarpOr[T any](p *T, fallback T) T {
|
||||
}
|
||||
|
||||
// UnwarpOrDefault returns the value from the pointer or the default value if the pointer is nil.
|
||||
// Play: https://go.dev/play/p/ZnGIHf8_o4E
|
||||
//
|
||||
// Play: https://go.dev/play/p/ZnGIHf8_o4E
|
||||
// Deprecated: Please use UnwrapOr
|
||||
func UnwarpOrDefault[T any](p *T) T {
|
||||
var v T
|
||||
|
||||
@@ -40,9 +49,24 @@ func UnwarpOrDefault[T any](p *T) T {
|
||||
return *p
|
||||
}
|
||||
|
||||
// UnwrapOr returns the value from the pointer or fallback if the pointer is nil.
|
||||
func UnwrapOr[T any](p *T, fallback ...T) T {
|
||||
if !IsNil(p) {
|
||||
return *p
|
||||
}
|
||||
if len(fallback) > 0 {
|
||||
return fallback[0]
|
||||
}
|
||||
var t T
|
||||
return t
|
||||
}
|
||||
|
||||
// ExtractPointer returns the underlying value by the given interface type
|
||||
// Play: https://go.dev/play/p/D7HFjeWU2ZP
|
||||
func ExtractPointer(value any) any {
|
||||
if IsNil(value) {
|
||||
return value
|
||||
}
|
||||
t := reflect.TypeOf(value)
|
||||
v := reflect.ValueOf(value)
|
||||
|
||||
@@ -56,3 +80,8 @@ func ExtractPointer(value any) any {
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// IsNil returns true if the given interface is nil or the underlying value is nil.
|
||||
func IsNil(i interface{}) bool {
|
||||
return i == nil || (reflect.ValueOf(i).Kind() == reflect.Ptr && reflect.ValueOf(i).IsNil())
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user