proposal: generics: allow additional constraints on method. #64846
Labels
generics
Issue is related to generics
LanguageChange
Proposal
v2
A language change or incompatible library change
Milestone
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:
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
{
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
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.
The text was updated successfully, but these errors were encountered: