Files
platform/pkg/u/u.go

112 lines
1.8 KiB
Go
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
package u
import (
"fmt"
"time"
)
// ====================
// 逻辑
// ====================
func Else[T any](v *T, or T) T {
if v == nil {
return or
} else {
return *v
}
}
func ElseTo[A any, B any](a *A, f func(A) B) *B {
if a == nil {
return nil
} else {
return P(f(*a))
}
}
// ====================
// 指针
// ====================
// P 原地创建值的指针
func P[T any](v T) *T {
return &v
}
// Z 转换值为不可空,如果值为 nil则返回其零值
func Z[T any](v *T) T {
if v == nil {
var zero T
return zero
}
return *v
}
// X 转换值为可空,如果值为零值,则返回 nil
func X[T comparable](v T) *T {
var zero T
if v == zero {
return nil
}
return &v
}
// ====================
// 数组
// ====================
func Map[T any, R any](src []T, convert func(T) R) []R {
dst := make([]R, len(src))
for i, item := range src {
dst[i] = convert(item)
}
return dst
}
// ====================
// 时间
// ====================
func DateHead(date time.Time) time.Time {
var y, m, d = date.Date()
return time.Date(y, m, d, 0, 0, 0, 0, date.Location())
}
func DateFoot(date time.Time) time.Time {
var y, m, d = date.Date()
return time.Date(y, m, d, 23, 59, 59, 999999999, date.Location())
}
func Today() time.Time {
return DateHead(time.Now())
}
func IsSameDate(date1, date2 time.Time) bool {
var y1, m1, d1 = date1.Date()
var y2, m2, d2 = date2.Date()
return y1 == y2 && m1 == m2 && d1 == d2
}
func IsToday(date time.Time) bool {
return IsSameDate(date, time.Now())
}
// ====================
// 错误
// ====================
func CombineErrors(errs []error) error {
var combinedErr error = nil
for _, err := range errs {
if err != nil {
if combinedErr == nil {
combinedErr = err
} else {
combinedErr = fmt.Errorf("%v; %w", combinedErr, err)
}
}
}
return combinedErr
}