Casting ulong to int with @nogc

Paul Backus snarwin at gmail.com
Wed Jul 28 17:58:00 UTC 2021


On Wednesday, 28 July 2021 at 17:41:04 UTC, Selim Ozel wrote:
> import std.conv:to;
>
> ```d
> import std.conv:to;
>
> @nogc int
> myFunction(ulong number){
> return to!int(number);
> }
> ```
>
> Since std.conv.to is a non at nogc myFunction throws a compiler 
> error. From a practical perspective length property of arrays 
> return ulong. What do you think is a reasonable way of casting 
> that into int with no-gc.

The reason `std.conv.to` doesn't work in `@nogc` is that it 
throws an exception when the conversion fails, and exceptions 
require the GC.

If you're ok with values larger than `int.max` causing overflow, 
you can just use `cast(int) number`. Otherwise, you will probably 
want to write your own conversion function that does overflow 
checking.


More information about the Digitalmars-d mailing list