-
Notifications
You must be signed in to change notification settings - Fork 17.6k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
proposal: spec: allow additional constraints on methods of generic types #64846
Comments
Duplicate of #49085 |
These are completely different things. Are you sure you have carefully read the community's proposals? @seankhliao |
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. |
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 |
This is not a dup. Reopening. |
Although this is (now) a dup of #65394, which has more comments. |
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: