How to return a reference to structs?

Paul Backus snarwin at gmail.com
Thu Nov 4 13:03:54 UTC 2021


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]);
}
```


More information about the Digitalmars-d-learn mailing list