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

feat: return nil for slice operations that received nil #409

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

Conversation

abemedia
Copy link

Amend slice functions to return nil if the collection argument is nil.

This is a non-breaking change because all built-ins etc. treat nil slices the same as zero length slices.

I also fixed some of the tests as they had expected and actual in the wrong order.

@samber
Copy link
Owner

samber commented Jun 28, 2024

Can you argue about returning nil instead of zero value (an empty array).

Because if I try to apply the same rule to other helpers, what would be the behavior of SumBy:

func SumBy[T any, R constraints.Float | constraints.Integer | constraints.Complex](collection []T, iteratee func(item T) R) R {
	var sum R = 0
	for _, item := range collection {
		sum = sum   iteratee(item)
	}
	return sum
}

@abemedia
Copy link
Author

abemedia commented Jul 6, 2024

Hi @samber

The behaviour of SumBy wouldn't change at all as iterating over a nil slice is a perfectly valid operation.

Thanks for approving! Just seen there's a bunch of conflicts so will fix ASAP.

@abemedia
Copy link
Author

abemedia commented Jul 7, 2024

Have fixed the conflicts. Regarding arguing why it should be nil, not zero, If I pass a nil slice into a function to remove elements and it was nil and then it comes back as a zero slice that feels semantically wrong. The behaviour of returning nils when that was passed in is also what the stdlib does in the slices package. See https://go.dev/play/p/kC2YOFdslWO

The reason I was inspired to fix this is because a load of my tests were breaking when I started using lo for filtering and mapping slices as our REST API was suddenly returning JSON arrays for fields which were meant to be nulls.

@abemedia
Copy link
Author

@samber any chance of getting this merged?

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.

None yet

2 participants