First Draft: cast(ref T)... as shorthand for *cast(T*)&...

Paul Backus snarwin at gmail.com
Wed Jan 22 19:17:06 UTC 2025


On Wednesday, 22 January 2025 at 07:12:08 UTC, Walter Bright 
wrote:
> On 1/20/2025 7:43 PM, Paul Backus wrote:
>> Would you be open to using a helper function if it had a 
>> shorter, less ugly name?
>
> The shorter the name, and the less ugly it is, the more it 
> risks breaking code. Overloading keywords is commonplace in 
> languages, and D, to avoid that problem.

I am confident that, if we put our minds to it, we can find a 
name which both satisfies your aesthetic sensibilities and 
carries minimal risk of breaking existing code.

For example:

* x.typePaint!T
* x.bytesAs!T
* x.transmute!T (from Rust [1])

All of these are as short as, or shorter than, `cast(ref T) x`, 
and none of them seem likely to break existing code.

Personally, I'm a fan of the name typePaint for this operation, 
since it's a term that's already used in the language 
specification ([2], [3], [4]).

[1] https://doc.rust-lang.org/std/mem/fn.transmute.html
[2] https://dlang.org/spec/expression.html#cast_class
[3] https://dlang.org/spec/expression.html#cast_array
[4] https://dlang.org/spec/expression.html#cast_static_array

> Consider the builtin associative arrays. These have been a big 
> success. All attempts at making it a template foundered on it 
> being less convenient to use.

Associative arrays are an extremely versatile and widely-used 
data structure, so there is a lot of value in making them as 
convenient as possible.

Reinterpreting casts, on the other hand, are a relatively niche, 
low-level operation. Most code never needs to use them at all, so 
there is not a lot of value in making them maximally convenient.

> One of the problems of relying on templates for basic things is 
> they aren't in the language specification, so people don't 
> realize they are there.

Just the other day, in the community Discord, I showed Steven 
Schvieghoffer--a long-time contributor to D--the section in the 
language spec about how `cast(S) expr` can be rewritten to 
`S(expr)` if S is a struct. [5] His exact reply was, "Oh wow. 
That isn't something I knew or expected."

Burying this feature in the specification for cast expressions 
would be, IMHO, a great way to ensure that hardly anybody ever 
finds out about it.

[5] https://dlang.org/spec/expression.html#cast_struct


More information about the dip.development mailing list