proposal: Go 2: Allow untyped parameters in function literals inside named types #68486
Closed
2 of 4 tasks
Labels
Milestone
Go Programming Experience
Experienced
Other Languages Experience
C, C++, TypeScript, Python, Groovy
Related Idea
Has this idea, or one like it, been proposed before?
This idea has been originally proposed in #30931, but closed due to inadequate syntax.
Does this affect error handling?
No.
Is this about generics?
No.
Proposal
In non-func named types, it is permitted to use untyped literals when instanciating:
This proposal extends this to a func named type:
Since function arguments and return values are already defined in the named type, it should be easy to infer them in the untyped function literal.
This change would make named functions with long definitions less repetitive:
Additionally, we could also allow parameter type inference in case variable-that-holds-a-func type is already defined:
Language Spec Changes
I am not that too familiar with technicalities of the spec, but I assume rules about anonymous functions would have to be relaxed to allow for untyped arguments:
In particular, in ParameterDecl, the Type would be optional:
Or the syntax itself should be separated, and FunctionLit should be defined with OptionallyTypedSignature which would have optional parameter declaration type.
This would require context-check of whether the function literal is inside of a named type or not:
I am not sure if this can be handled by syntax parsing itself or is this a semantic property.
Informal Change
In Go 1.22 and earlier, when creating anonymous functions, we had to specify all argument types in advance, regardless of whether or not .
That leads to a lot of unnecessary typing, e.g.:
This change would allow us to leave out the function parameter types:
Is this change backward compatible?
Yes.
Orthogonality: How does this change interact or overlap with existing features?
The new syntax is just a shorthand for the fully-typed function literal, similar to how
name ":=" type "(" value ")" | value
operator is a shorthand for"var" name type "=" value
.Would this change make Go easier or harder to learn, and why?
It wouldn't change the ease of learning Go significantly, similar to
:=
operator.Cost Description
Increased complexity of the spec and parser.
Changes to Go ToolChain
All tools that deal with language syntax.
Performance Costs
Compile time cost will probably be insignificant. Run time cost will be zero since code will compile exactly the same.
Prototype
I don't have the necessary experience with Go compiler to do this.
The text was updated successfully, but these errors were encountered: