Why is the BinarySearch function in the slices package defined like this:
func BinarySearch[S ~[]E, E cmp.Ordered](x S, target E) (int, bool)
And not like this:
func BinarySearch[E cmp.Ordered](x []E, target E) (int, bool)
I tried to write code that works with the first one and does not compile with the second definition. But I'm new to go and I have no idea.
BinarySearch can be written either way; in fact the definition used to be:
func BinarySearch[E cmp.Ordered](x []E, target E) (int, bool)
It was changed to:
func BinarySearchFunc[S ~[]E, E, T any](x S, target T, cmp func(E, T) int) (int, bool)
following the proposal in this issue. The commit explains the reason for the change:
slices: consistently use S ~[]E
Make all functions use a constraint S ~[]E even if they don't return the slice type. This makes explicitly instantiating the functions more consistent: you don't have to remember which take ~[]E and which do not. It also permits inferring the type when passing one of these functions to some other function that is using a named slice type.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With