github.com/jxskiss/gopkg/v2@v2.14.9-0.20240514120614-899f3e7952b4/utils/ptr/generic.go (about)

     1  package ptr
     2  
     3  // Copy returns a shallow copy of the given pointer of any type.
     4  // If p is nil, it returns nil.
     5  func Copy[T any](p *T) (ret *T) {
     6  	if p != nil {
     7  		x := *p
     8  		ret = &x
     9  	}
    10  	return
    11  }
    12  
    13  // Deref returns the value pointed by pointer p.
    14  // If p is nil, it returns zero value of type T.
    15  func Deref[T any](p *T) (ret T) {
    16  	if p != nil {
    17  		ret = *p
    18  	}
    19  	return
    20  }
    21  
    22  // Ptr returns copies v of any type and returns a pointer.
    23  func Ptr[T any](v T) *T {
    24  	return &v
    25  }
    26  
    27  // NotZero returns a pointer to v if v is not zero value of it's type,
    28  // else it returns nil.
    29  func NotZero[T comparable](v T) (ret *T) {
    30  	var zero T
    31  	if v != zero {
    32  		ret = &v
    33  	}
    34  	return
    35  }