Literal types
IchorDev
zxinsworld at gmail.com
Fri Jul 4 16:16:05 UTC 2025
On Wednesday, 25 June 2025 at 17:56:09 UTC, Quirin Schroll wrote:
> I don’t know if I’m getting this 100% correct, but saying `[1,
> 2]` is an `int[]` isn’t the full story since it’s more like an
> `int[2]` that “decays” to a `int[]` (which usually ends up on
> the heap) unless you “catch” it early enough. Catching such a
> literal isn’t too difficult, the `staticArray` function does it.
There’s a really clever idea in here somewhere but I think you
didn’t quite hit the nail on the head. The one-way implicit
casting of literals often gets in my way…
```
auto x = 1;
ushort y = x; //ERR: `1` is an `int`… ugh
ushort z = 1; //OK: `1` is actually `ushort` now
auto a = [1,2];
ubyte[] b = a.dup(); //ERR: `[1,2]` is an `int[]`… ugh
ubyte[] c = [1,2]; //OK: on second thought, `[1,2]` can totally
be a `ubyte[]`…
```
One thing that could mitigate this is having explicit suffixes
for char, byte, and short. But what would be really nice is if
the language could keep track of when a variable’s type was
inferred from nothing but a literal, and then allow the usual
type conversion restrictions to be bent a little based on how the
literal could’ve been interpreted as a different type.
It’s a similar idea to https://dlang.org/spec/type.html#vrp which
never accounts for variables that have just been unconditionally
assigned a literal value.
Oddly, the idea that I described already exists for enums:
```d
enum int[] x = [1,2];
ushort[] y = x; //no error?!
ushort[2] z = x; //still no error!!?!
```
Hopefully that makes sense.
TL;DR: Let variables that are initialised/unconditionally
assigned literals follow the same implicit cast rules as the
literal, meaning that `int x=1; byte y=x;` compiles since `1` can
be inferred as a byte.
More information about the dip.ideas
mailing list