github.com/mitranim/gg@v0.1.17/ptr.go (about) 1 package gg 2 3 /* 4 Takes an arbitrary value and returns a non-nil pointer to a new memory region 5 containing a shallow copy of that value. 6 */ 7 func Ptr[A any](val A) *A { return &val } 8 9 /* 10 If the pointer is nil, uses `new` to allocate a new value of the given type, 11 returning the resulting pointer. Otherwise returns the input as-is. 12 */ 13 func PtrInited[A any](val *A) *A { 14 if val != nil { 15 return val 16 } 17 return new(A) 18 } 19 20 /* 21 If the outer pointer is nil, returns nil. If the inner pointer is nil, uses 22 `new` to allocate a new value, sets and returns the resulting new pointer. 23 Otherwise returns the inner pointer as-is. 24 */ 25 func PtrInit[A any](val **A) *A { 26 if val == nil { 27 return nil 28 } 29 if *val == nil { 30 *val = new(A) 31 } 32 return *val 33 } 34 35 /* 36 Zeroes the memory referenced by the given pointer. If the pointer is nil, does 37 nothing. Also see the interface `Clearer` and method `.Clear` implemented by 38 various types. 39 */ 40 func PtrClear[A any](val *A) { 41 if val != nil { 42 *val = Zero[A]() 43 } 44 } 45 46 // Calls `PtrClear` and returns the same pointer. 47 func PtrCleared[A any](val *A) *A { 48 PtrClear(val) 49 return val 50 } 51 52 // If the pointer is non-nil, dereferences it. Otherwise returns zero value. 53 func PtrGet[A any](val *A) A { 54 if val != nil { 55 return *val 56 } 57 return Zero[A]() 58 } 59 60 // If the pointer is nil, does nothing. If non-nil, set the given value. 61 func PtrSet[A any](tar *A, val A) { 62 if tar != nil { 63 *tar = val 64 } 65 } 66 67 /* 68 Takes two pointers and copies the value from source to target if both pointers 69 are non-nil. If either is nil, does nothing. 70 */ 71 func PtrSetOpt[A any](tar, src *A) { 72 if tar != nil && src != nil { 73 *tar = *src 74 } 75 } 76 77 /* 78 If the pointer is non-nil, returns its value while zeroing the destination. 79 Otherwise returns zero value. 80 */ 81 func PtrPop[A any](src *A) (out A) { 82 if src != nil { 83 out, *src = *src, out 84 } 85 return 86 }