Skip to content

feat: add GetOrZero #28

@jay-babu

Description

@jay-babu

Currently the Get method returns an error if null or unspecified, which makes sense when getting however if a user is explicitly calling a method named something like GetOrZero, their intention is to get the Zero value. The problem stems from having to ignore the error which can cause issues / annoyances with linters. This also allows using Nullable more easily as you can just add this everywhere instead of having a migration from bool -> Nullable[bool] once the use case comes up.

The method's signature would be pretty simple.

current implementation.

func (t Nullable[T]) Get() (T, error) {
	var empty T
	if t.IsNull() {
		return empty, errors.New("value is null")
	}
	if !t.IsSpecified() {
		return empty, errors.New("value is not specified")
	}
	return t[true], nil
}

addition:

func (t Nullable[T]) GetOrZero() T {
	val, _ := Get()
    return val
}

I am willing to open a PR if this is approved. Thank you!

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions