How to return a reference to structs?

Andrey Zherikov andrey.zherikov at gmail.com
Sat Nov 6 12:05:39 UTC 2021


On Saturday, 6 November 2021 at 04:28:05 UTC, Ali Çehreli wrote:
> On 11/5/21 5:43 PM, Andrey Zherikov wrote:
>
> In case others want to work, here are the modules that need to 
> be imported:
>
> import std.algorithm;
> import std.range;
> import std.stdio;
>
> > struct A {}
> > struct B
> > {
> >      A[] ar = [A.init];
> >      size_t[] idx = [0];
>
> I don't know why but those initial values are the reason for 
> the problem. It works without them.

`get()` will return nothing in this case. But I can make them non 
empty in another way:

```d
import std;

struct A {}
struct B
{
     A[] ar;
     size_t[] idx;

     A*[] get()
     {
         return idx.map!((idx) => &ar[idx]).array;
     }
}

auto foo()
{
     B b;
     b.ar ~= A.init;
     b.idx ~= 0;
     return b.get();
}

void main()
{
     writeln(foo());
     pragma(msg, foo());
}
```

Some one can complain that `foo()` returns pointers that are not 
available in CTFE but remember that the real code is more complex 
and `foo()` cam be return just length (`return b.get().length;`) 
having the same result.

Basically I have a collection of data (`A[] ar`), different 
addressing through the indexes (multiple `size_t[] idx`) and I 
want to manipulate these objects through indexes. If there is 
another way to achieve the same in CFTE, I'd like to hear.


More information about the Digitalmars-d-learn mailing list