Accessing part of a struct in an easy way

Paolo Invernizzi via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Mon Jul 3 10:13:14 PDT 2017


On Monday, 3 July 2017 at 16:41:51 UTC, vit wrote:
> On Monday, 3 July 2017 at 13:53:45 UTC, Paolo Invernizzi wrote:
>> [...]
>
> //https://dpaste.dzfl.pl/d59469c264b2
>
> import std.algorithm : map, copy, equal;
> import std.range : iota;
>
> struct Foo {
>     int[3] a;
>     string[2] b;
> }
>
> ref T first(R : T[], T)(ref R x,){return x[0];}
> ref T second(R : T[], T)(ref R x){return x[1];}
>
> void worksOnA(R : int[N], size_t N)(ref R r) {
> 	iota(1, N+1)
> 		.map!(x => cast(int)x*2)
> 		.copy(r[]);
> }
> void worksOnB(string[] r) { }
>
>
> void main(){
> 	auto foo = Foo();
> 	
> 	foo.a.first = 1;
> 	foo.a.second = 2;
> 	assert(foo.a.first == 1);
> 	assert(foo.a.second == 2);
>
> 	
> 	foo.b.second = "test";
> 	assert(foo.b.first == "");
> 	assert(foo.b.second == "test");
> 	
> 	foo.a.worksOnA();
> 	assert(foo.a[].equal([2, 4, 6]));
>
> }

Thanks for your solution, Vic!

It's not exactly the same, as first and second should be struct 
with partial fields from Foo, of different types.

/Paolo


More information about the Digitalmars-d-learn mailing list