Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

ADDED: Nillable function #501

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open

ADDED: Nillable function #501

wants to merge 1 commit into from

Conversation

Nizom98
Copy link

@Nizom98 Nizom98 commented Jul 18, 2024

This function helps you not to check the input parameter for nil every time.

@samber
Copy link
Owner

samber commented Jul 21, 2024

Why are you limiting this helper to pointers?

The current lo.Coalesce helper returns the first non-zero argument.

I wonder if you should call it lo.CoalesceF instead. What about chaining a list of callbacks with vaargs?

If your first argument is a value instead of func, it would be a good use case for the lo.Identity helper suggested in #420.

// values
lo.Coalesce(0, 42, 21) // 42

// func
lo.CoalesceF(returnsZero, returnsFortyTwo, returnsTwentyOne) // 42

// mix
lo.CoalesceF(returnsZero, lo.Identity(42), returnsTwentyOne) // 42

WDYT ?

@Nizom98
Copy link
Author

Nizom98 commented Jul 21, 2024

Thank you for your comment.

The current lo.Coalesce helper returns the first non-zero argument.

The goal of Nillable function is not returning non-nil argument. The goal is simplify converting between structs.
For example

type type1 struct {
	field1 string
}
type type2 struct {
	field2 string
}


// I need convert "type1" fields into "type2".
// The first way I can do is write "convert" function for all types.
type2Val := convType1ToType2(type1Val)
func convType1ToType2(in *type1) *type2 {
	if IsNil(nil) {
		return nil
	}
	return &type2{field2: in.field1}
}


// The second way to do this is the Nillable function.
// In this case I do not need check every time, that the inout parameter is "nil" and I do not write converter function for all types. 
type2Val := Nillable(type1Val, func(in *type1) *type2 {
	return &type2{field2: in.field1}
})

@Nizom98
Copy link
Author

Nizom98 commented Jul 21, 2024

Why are you limiting this helper to pointers?

If we will use non-pointer type, I could not determine default value to return.
Here is an example.

func Nillable[T, RT any](v T, fn func(T) RT) RT {
	if IsNil(v) {
		// TODO: should we return new(RT) or *new(RT)?
                // We cannot return new(RT), because return type is not a pointer. 
	}
	return fn(v)
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants