Type Inference for Struct/Enum Literals
IchorDev
zxinsworld at gmail.com
Sat Jul 6 11:04:16 UTC 2024
On Saturday, 6 July 2024 at 02:49:32 UTC, Steven Schveighoffer
wrote:
> One might argue that `$.symbol` could mean "global symbol"
> instead (or something else).
Hey, not a bad idea! I think that could work for struct literals
like `$(a, b, c)`, and then they could both use the same prefix.
Probably not with `$` though—Atila said it was ‘unsightly’.
That said, the plain `.symbol` does look rather more 'sightly'
than having any prefix for enum literals in my opinion. I was
very into the idea of using `\` during my original proposal, but
I remember there being some really stupid issue with it. Might be
worth trying it again though.
> Already there is pushback from the language maintainers on the
> concept itself (from the original review).
On the contrary, Walter was pretty much on-board with enum
literal type inference, he just didn't like it working with
function overloads because he was concerned about performance
(which I'm pretty sure UplinkCoder already solved), and he didn't
want there to be a prefix; you'd just write the enum member like
you would in C. Like so:
```d
enum A{ a,b,c,d }
struct S{ A one, two; }
void main(){
A myA1 = b; // myA1 = A.b
A myA2 = b | c; // myA2 = A.d
auto myA3 = b; // error, b is undefined
S myS;
myS.one = c; // myB.one = A.c
myS.two = d; // myB.two = A.d
}
```
Back then I was strongly against this syntax due to its
ambiguity, breaking existing code, and also because it means you
always have to check if the type of an assignment/parameter is an
enum (so the best-case performance is much worse). I think if it
was the only choice it'd be better than nothing, but I think it'd
cause people a lot of headaches compared to a more explicit
syntax. For struct literals though, I think implementing the same
prefix-less syntax would be a complete and utter nightmare.
> I very much enjoyed it in my swift programs.
Ah yes, and Swift enums are already sumtypes. I guess there might
be potential for sumtype literal type inference down the road.
> I would guess that the best possibility to be accepted would be
> to have syntax that doesn't conflict with existing syntax.
I doubt it. My original proposal didn't conflict with any
existing syntax, whereas Walter's counter-proposal would've
broken a fair bit of code.
A lot of people said they'd only be on board if I replaced the
module scope operator, which *I* was against at the time because
I didn't want the feature to break anyone's code. With editions
on the horizon, I'm down for pretty much whatever syntax Walter
and Atila could agree on.
More information about the dip.ideas
mailing list