zlacker

[return to "Go(lang): Robust generic functions on slices"]
1. gslall+Ng3[view] [source] 2024-02-24 09:47:08
>>signa1+(OP)
> func Index[S ~[]E, E comparable](s S, v E) int {

After seeing this signature, I think that Go is giving up on it's simpleness principle.

◧◩
2. quickt+wj3[view] [source] 2024-02-24 10:30:40
>>gslall+Ng3
what does the ~ do here anyway?
◧◩◪
3. onefiv+qk3[view] [source] 2024-02-24 10:44:03
>>quickt+wj3
type Something []string

ensure that the underlying type is a slice

◧◩◪◨
4. shakow+6l3[view] [source] 2024-02-24 10:55:22
>>onefiv+qk3
Why do you need a tilda for `S ~[]E`, but not for `E comparable`?

Both are type-constraining annotations, so why two syntaxes?

◧◩◪◨⬒
5. ithkui+In3[view] [source] 2024-02-24 11:34:22
>>shakow+6l3
Because when you define a "type Foo []int" you're definig a new type Foo that is not the same type as []int.

So if the type parameter said "[]E" where E is a comparable then "Foo" wouldn't be allowed because Foo is not the same type as "[]int" (for that you'd need a type alias i.e "type Foo = []int". This is by design since it allows you to define new types you don't want to get accidentally used where you don't want them to.

When defining library functions that are truly generic you may want instead to let them be used on the "underlying type". For example, Sort library authors decided that generally you want it to just work on the underlying type and that's why they added ~ in front of the generic type. Otherwise every invocation of Sort you'd need to convert the type e.g. "slices.Sort([]int(myfoo))".

The other type parameter "E comparable" doesn't need the tilde because "comparable" is not an actual type but a type constraint.

A type constraint is an interface that defines the set of permissible type arguments for the respective type parameter and controls the operations supported by values of that type parameter.

You don't need a tilde because any type that implements that constraint will be accepted. Also any type implementing a constraint that embeds that constraint also works

[go to top]