- Published on
Generics in Go
248 words2 min read
Percent
function that can work with either int
or float64
types.
func Percent[T int | float64](percent T, number T) float64 {
return ((float64(number) * float64(percent)) / float64(100))
}
ArePointersEqual
function that determines if two pointers are equal. Only works with either int
or string
types.
func ArePointersEqual[T int | string](a *T, b *T) bool {
return a == nil && b == nil || a != nil && b != nil && *a == *b
}
Convert to and from pointers
func ToPointer[T any](t T) *T {
return &t
}
func FromPointer[T any](t *T) T {
if t == nil {
return *new(T)
}
return *t
}