Skip to content

Commit

Permalink
Add generic ToOrNil
Browse files Browse the repository at this point in the history
  • Loading branch information
AlekSi committed Aug 21, 2021
1 parent 2eade2a commit 47b3772
Showing 1 changed file with 15 additions and 2 deletions.
17 changes: 15 additions & 2 deletions generic.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,12 +4,25 @@ func To[T any](t T) *T {
return &t
}

func ToOrNil[T comparable](t T) *T {
if z, ok := interface{}(t).(interface{ IsZero() bool }); ok {
if z.IsZero() {
return nil
}
return &t
}

var zero T
if t == zero {
return nil
}
return &t
}

func Get[T any](t *T) T {
if t == nil {
var zero T
return zero
}
return *t
}

// No `func ToOrNil[T any](t T) *T` due to time.Time.Equal

0 comments on commit 47b3772

Please sign in to comment.