How to replicate an Error: scope variable `old` assigned to `ref` variable `ctx` with longer lifetime?

matheus matheus at gmail.com
Tue May 13 11:55:21 UTC 2025


On Monday, 12 May 2025 at 22:57:22 UTC, Dennis wrote:
> On Monday, 12 May 2025 at 21:46:04 UTC, matheus wrote:
>> I saw a post 
>> (https://forum.dlang.org/post/aklmfkzqpsraprjfxsjh@forum.dlang.org) by Dennis where he gives an example:
>>
>> So I'd like to try it out, so I wrote the snippet below:
>>
>> @safe
>>
>> import std;
>>
>> struct S{}
>
> Make sure S contains at least one pointer, and compile with 
> -preview=dip1000

First thanks for replying!

Unfortunately adding the pointer gives me another error:

import std;

struct S{ int *p; }

void f(ref scope S ctx) {
     const old = ctx;
     g(ctx);
     ctx = old;
}

void g(ref scope S ctx) {
     S a;
     ctx = a;
}

void main(){
    S i;
    f(i);
}

onlineapp.d(8): Error: cannot implicitly convert expression `old` 
of type `const(S)` to `S`

If I replace:

  ctx = old;

To:

  ctx = cast(S)old;

It compiles without any error.

https://run.dlang.io/?compiler=dmd&args=-preview%3Ddip1000&source=import%20std;%0A%0Astruct%20S%7B%20int%20*p;%20%7D%0A%0Avoid%20f(ref%20scope%20S%20ctx)%20%7B%0A%20%20%20%20const%20old%20%3D%20ctx;%0A%20%20%20%20g(ctx);%0A%20%20%20%20ctx%20%3D%20cast(S)old;%0A%7D%0A%0Avoid%20g(ref%20scope%20S%20ctx)%20%7B%0A%20%20%20%20S%20a;%0A%20%20%20%20ctx%20%3D%20a;%0A%7D%0A%0Avoid%20main()%7B%0A%20%20%20S%20i;%0A%20%20%20f(i);%0A%7D

Matheus.


More information about the Digitalmars-d-learn mailing list