cast(string) for mutable array

user1234 user1234 at 12.de
Fri Jul 31 14:53:23 UTC 2026


On Friday, 31 July 2026 at 13:52:12 UTC, Vindex9 wrote:
> Is this code normal? Why can't it be marked with `@safe`? Can 
> only `idup` be used for `@safe` in such cases?
>
> ```d
> string fn() @trusted pure {
>     char[] arr;
>     // some manipulations...
>     return cast(string) arr;
> }
> ```
>
> Where is the line between cases where the `@trusted` tag can be 
> used and cases where the `@system` tag can be used?

The cast is not memory safe because it breaks the type system 
(`string` element-type is `immutable(char)` and `immutable` is 
part of the type). So callers may think that the elements are 
indeed immutable while they are actually allowed to change.

But for a simple example like this it's obvious that the problem 
wont happen (i.e mutation of the elements), hence you can mark 
the function `@trusted`.

spec: https://dlang.org/spec/memory-safe-d.html


More information about the Digitalmars-d-learn mailing list