Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do functions in the slices package define a type parameter for the slice argument?

Tags:

generics

go

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.

like image 341
Bomgar Avatar asked Dec 29 '25 06:12

Bomgar


1 Answers

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.

like image 132
Brits Avatar answered Dec 30 '25 21:12

Brits



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!