goext/langext/coalesce.go

72 lines
895 B
Go
Raw Normal View History

2022-10-27 16:00:57 +02:00
package langext
import (
"fmt"
"time"
)
func Coalesce[T any](v *T, def T) T {
if v == nil {
return def
} else {
return *v
}
}
func CoalesceString(s *string, def string) string {
if s == nil {
return def
} else {
return *s
}
}
func CoalesceInt(i *int, def int) int {
if i == nil {
return def
} else {
return *i
}
}
func CoalesceInt32(i *int32, def int32) int32 {
if i == nil {
return def
} else {
return *i
}
}
func CoalesceBool(b *bool, def bool) bool {
if b == nil {
return def
} else {
return *b
}
}
func CoalesceTime(t *time.Time, def time.Time) time.Time {
if t == nil {
return def
} else {
return *t
}
}
func CoalesceStringer(s fmt.Stringer, def string) string {
if IsNil(s) {
return def
} else {
return s.String()
}
}
2023-03-21 16:00:15 +01:00
func SafeCast[T any](v any, def T) T {
switch r := v.(type) {
case T:
return r
default:
return def
}
}