How to return a reference to structs?

Andrey Zherikov andrey.zherikov at gmail.com
Thu Nov 4 18:21:06 UTC 2021


On Thursday, 4 November 2021 at 13:03:54 UTC, Paul Backus wrote:
> On Thursday, 4 November 2021 at 11:26:30 UTC, Andrey Zherikov 
> wrote:
>> I have the following code example:
>>
>> ```d
>> struct A{}
>>
>> A[5] a;
>> ulong[] idx = [1,3,4];
>>
>> auto get()
>> {
>>     return idx.map!(_ => a[_]);
>> }
>>
>> foreach(i; 0 .. a.length)
>>     write(&a[i], " ");
>> writeln;
>>
>> foreach(ref b; get())
>>     write(&b, " ");
>> writeln;
>> ```
>>
>> How can I change `get` function so it returns the references 
>> to the content in `a`?
>
> Have the lambda return by reference:
>
> ```d
> auto get()
> {
>     return idx.map!(ref (i) => a[i]);
> }
> ```

Making this example a bit complex: I want `get` to return 
additional data to the reference. How should I change the lambda 
then?
```d
auto get()
{
     return idx.map!(ref (i) => tuple(a[i], i)); // return ref and 
index for simplicity
}
```


More information about the Digitalmars-d-learn mailing list