help cast

Steven Schveighoffer schveiguy at yahoo.com
Mon Mar 19 11:20:05 UTC 2018


On 3/18/18 4:07 PM, Jonathan M Davis wrote:

> That's exactly what it's doing, and when you have multiple elements in the
> literal, it quickly gets a lot more pleasant than casting each element
> individually. e.g.
> 
> cast(ubyte[])[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
> 
> vs
> 
> [cast(ubyte)0, cast(ubyte)1, cast(ubyte)2, cast(ubyte)3, cast(ubyte)4,
>   cast(ubyte)5, cast(ubyte)6, cast(ubyte)7, cast(ubyte)8, cast(ubyte)9,
>   cast(ubyte)10]
> 
> I use this trick all the time when creating arrays of integral types smaller
> than int, precisely because casting each element is a royal pain and way
> harder to read.

Let me adjust your example a bit, and see if you still agree:

auto bytes = cast(ubyte[])[55_444, 289, 1_000_000, 846, 123_456_789];

writeln(bytes); // [148, 33, 64, 78, 21]

I have used cast(ubyte[]) to get ubytes as well, but I normally would do 
this for values that actually *could be* ubytes. for values higher than 
ubytes, I would not have expected implicit truncation. It's especially 
confusing to someone who has seen when you cast an int[] to a ubyte[], 
and gets the bytes for that same data. When I use cast(ubyte[]), I took 
it to mean "pretend this is a ubyte[] literal", not "cast each element 
to ubyte".

I can also see this biting someone who has a long set of ubytes, and 
accidentally does one that is larger than 255.

-Steve


More information about the Digitalmars-d mailing list