Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions changes/20260318100334.feature
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
:sparkles: `[field]` Add a utility to set an optional field to nil if empty
5 changes: 5 additions & 0 deletions utils/field/fields.go
Original file line number Diff line number Diff line change
Expand Up @@ -225,6 +225,11 @@ func ToOptionalOrNilIfEmpty[T any](v T) *T {
return ptr.ToOrNilIfEmpty(v)
}

// NilIfEmpty returns the given pointer unless it is empty and in that case returns nil. It is similar to ToOptionalOrNilIfEmpty but works on reference.
func NilIfEmpty[T any](v *T) *T {
return ptr.NilIfEmpty(v)
}

// ToOptional returns a pointer to the given field value.
func ToOptional[T any](v T) *T {
return ptr.To[T](v)
Expand Down
5 changes: 5 additions & 0 deletions utils/field/fields_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -296,6 +296,11 @@ func TestOptionalField(t *testing.T) {
}
}

func TestOptionalField_Nil(t *testing.T) {
var test int
assert.Nil(t, NilIfEmpty(&test))
}

func TestEqual(t *testing.T) {
type T int
assert.True(t, Equal[T](nil, nil))
Expand Down
14 changes: 14 additions & 0 deletions utils/mocks/mock_saga.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

7 changes: 6 additions & 1 deletion utils/ptr/pointer.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,10 +12,15 @@ func To[T any](v T) *T {
// Emptiness is determined via utils/reflection.IsEmpty (e.g. "", whitespace-only strings, 0, false, nil,
// empty slices/maps, etc.).
func ToOrNilIfEmpty[T any](v T) *T {
return NilIfEmpty(To[T](v))
}

// NilIfEmpty returns v if v is not considered empty; otherwise it returns nil.
func NilIfEmpty[T any](v *T) *T {
if value.IsEmpty(v) {
return nil
}
return To[T](v)
return v
}

// From returns the value pointed to by v.
Expand Down
14 changes: 14 additions & 0 deletions utils/transaction/saga/mock_test.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Loading