github.com/searKing/golang/go@v1.2.117/exp/types/pointer_value.go (about)

     1  // Copyright 2022 The searKing Author. All rights reserved.
     2  // Use of this source code is governed by a BSD-style
     3  // license that can be found in the LICENSE file.
     4  
     5  package types
     6  
     7  // Pointer returns a pointer to the value passed in.
     8  func Pointer[T any](v T) *T {
     9  	return &v
    10  }
    11  
    12  // Value returns the value of the pointer passed in or
    13  // "" if the pointer is nil.
    14  func Value[T any](v *T) T {
    15  	if v != nil {
    16  		return *v
    17  	}
    18  	var zero T
    19  	return zero
    20  }
    21  
    22  // PointerSlice converts a slice of values into a slice of pointers
    23  func PointerSlice[S ~[]E, V []*E, E any](src S) V {
    24  	dst := make(V, len(src))
    25  	for i := 0; i < len(src); i++ {
    26  		dst[i] = &(src[i])
    27  	}
    28  	return dst
    29  }
    30  
    31  // ValueSlice converts a slice of pointers into a slice of values
    32  func ValueSlice[S ~[]*E, V []E, E any](src S) V {
    33  	dst := make(V, len(src))
    34  	for i := 0; i < len(src); i++ {
    35  		if src[i] != nil {
    36  			dst[i] = *(src[i])
    37  		}
    38  	}
    39  	return dst
    40  }
    41  
    42  // PointerMap converts a map of values into a map of pointers
    43  func PointerMap[M ~map[K]V, N map[K]*V, K comparable, V any](src M) N {
    44  	dst := make(N)
    45  	for k, val := range src {
    46  		v := val
    47  		dst[k] = &v
    48  	}
    49  	return dst
    50  }
    51  
    52  // ValueMap converts a map of string pointers into a string map of values
    53  func ValueMap[M ~map[K]*V, N map[K]V, K comparable, V any](src M) N {
    54  	dst := make(N)
    55  	for k, val := range src {
    56  		if val != nil {
    57  			dst[k] = *val
    58  		}
    59  	}
    60  	return dst
    61  }