Description
Go Programming Experience
Experienced
Other Languages Experience
C++, C, Perl
Related Idea
- Has this idea, or one like it, been proposed before?
- Does this affect error handling?
- Is this about generics?
- Is this change backward compatible? Breaking the Go 1 compatibility guarantee is a large cost and requires a large benefit
Has this idea, or one like it, been proposed before?
No
Does this affect error handling?
No
Is this about generics?
No
Proposal
Extend the syntax around initializing struct objects with embedded structs to allow the elision of the name of the embedded struct (as can be done when using the resultant object in a dot expression).
For instance:
given
type A struct {
X int
}
and
type B struct {
A
Y int
}
then to initialize an object of type B we must
b := B{
A: A{X: 1},
Y: 2,
}
but to use it we can ...
b.X = 3
or ...
b.A.X = 4
The proposal is to provide the same syntactic sugar for initialization as we have when using the value:
b := B{
X: 1,
Y: 2,
}
As with the dot-expression this would only apply to anonymous, embedded structs.
If there are any ambiguous names you can return the same ambiguous selector
error as is given when using ambiguous names in a dot-expression.
This will have the advantage of reducing the amount of code you need to write in order to initialize an object. The code is repetitious and verbose and approving this proposal would make it much more concise.
For instance, initializing an embedded struct S from package p with member X currently requires:
S: p.S{X: ...}
and could be replaced with:
X: ...
Language Spec Changes
No response
Informal Change
No response
Is this change backward compatible?
Yes, it doesn't break the Go 1 compatibility guarantee.
For the before and after examples see the Proposal (above).
Orthogonality: How does this change interact or overlap with existing features?
This should have no interaction with the rest of the language. It just allows the programmer to type less code when initializing objects. There will be no change to the performance of the executable.
Would this change make Go easier or harder to learn, and why?
It should make Go easier to learn since it removes a discrepancy between initialization and use of objects.
Cost Description
The compiler will become more complicated since there will need to be more code to parse the initialization statements but the generated code would be identical.
Changes to Go ToolChain
The Go compiler
Performance Costs
There will be a small increase in compile time; no change in run time
Prototype
No response