golang / go

The Go programming language
https://go.dev
BSD 3-Clause "New" or "Revised" License
123.97k stars 17.66k forks source link

proposal: spec: allow additional constraints on methods of generic types #64846

Open leaxoy opened 10 months ago

leaxoy commented 10 months ago

Proposal Details

Proposal

Generic structures can have type parameters and constraints, and generic structures can also have methods. but there is no way to add more constraints on the methods of generic structures.

Let's look at a classic example, sorting slices:


type Slice[E cmp.Ordered] struct {}

func (s *Slice[E]) Sort() {}

// or 

type Slice[E any] struct {}
func Sort[E cmp.Ordered](s *Slice[E]) {}

// but now, we can't write such code
type Slice[E any] struct {}

func (s *Slice[E cmp.Ordered]) Sort() {}

Some currently feasible methods have some inconveniences

Adding narrower constraints on types also narrows the usefulness of the structure.

Top-level functions will directly affect the user experience, and some chain operations will have to be split into multiple lines.

Therefore I propose that the language should provide the ability to add type constraints on methods of generic structures.


Some possible syntax:

Option 1

using where clause at the end of method signature, but before {

func (s *Slice[E]) Sort() where E: cmp.Ordered {}

This method can only be accessed when E satisfies the constraint cmp.Ordered, otherwise it cannot be accessed.

Other languages, such as c#/rust/swift, provide similar capabilities.

This approach is closer to common practice in other languages, but requires the introduction of a keyword.

Option 2

add constraints near E

func (s *Slice[E cmp.Ordered]) Sort() {}

As far as I know, this approach has not been used in other languages.

This method does not require the introduction of additional keywords, but it looks a bit strange.


This is the complete proposal and some attempts at syntax.

seankhliao commented 10 months ago

Duplicate of #49085

leaxoy commented 10 months ago

These are completely different things. Are you sure you have carefully read the community's proposals? @seankhliao

leaxoy commented 10 months ago

That issue propose add new type parameters, but this is not add new type parameters. It't just narrow the existing type parameter in specific scenarios.

seankhliao commented 10 months ago

if you consider the fact that the receiver is just another argument to the function, then it's the same: you're introducing new constraints in a method

ianlancetaylor commented 9 months ago

This is not a dup. Reopening.

ianlancetaylor commented 9 months ago

Although this is (now) a dup of #65394, which has more comments.