Cast converts AA to rvalue?

ag0aep6g anonymous at example.com
Wed Aug 10 17:41:46 UTC 2022


On Wednesday, 10 August 2022 at 17:14:08 UTC, Johan wrote:
> ```
> void f() {
>     aa[1] = 1; // error
> }
> shared static this()
> {
>     f();
> }
> ```
>
> I had considered it, but discarded it... `f` is also a template 
> in our code. Your remark made me check again, and the call 
> chain is short, perhaps I'll convert `f` to a template mixin... 
> Unfortunately doesn't work: "immutable variable `aa` 
> initialization is not allowed in nested function `f`".

If you can build a mutable version of the array in a `pure` 
function, you can do it like this:

```d
int[int] make_aa() pure
{
     int[int] maa;
     maa[1] = 1; /* or function calls, or whatever */
     return maa;
}
immutable int[int] aa;
shared static this()
{
     aa = make_aa();
}
```

If you can't do it in a `pure` function, you can do it with a 
cast: `aa = cast(immutable) make_aa();`.

Casting from mutable to immutable is better, because it does not 
have undefined behavior (as long as you don't use a mutable 
reference later). Your casting away immutable and then mutating 
does have undefined behavior.


More information about the Digitalmars-d-learn mailing list