gitee.com/quant1x/num@v0.3.2/kind/default.go (about)

     1  package kind
     2  
     3  import "math"
     4  
     5  var (
     6  	stringNaN  = "NaN"
     7  	floatNaN   = math.NaN()
     8  	float32NaN = float32(floatNaN)
     9  	float64NaN = float64(floatNaN)
    10  )
    11  
    12  // Default 设定泛型默认值, 0或者NaN
    13  func Default[T BaseType]() T {
    14  	var d any
    15  	var v T // for zero value
    16  	switch any(v).(type) {
    17  	case bool:
    18  		d = false
    19  	case int8, uint8, int16, uint16, int32, uint32, int64, uint64, int, uint, uintptr:
    20  		d = v
    21  	case float32:
    22  		d = float32NaN
    23  	case float64:
    24  		d = float64NaN
    25  	case string:
    26  		d = stringNaN
    27  	default:
    28  		// 默认零值
    29  		d = v
    30  	}
    31  
    32  	return d.(T)
    33  }