1 /// 2 module scrapd.assign; 3 4 /// 5 void assign(T, U)(ref T target, scope U source) 6 { 7 static foreach (prop; __traits(allMembers, T)) 8 { 9 static if (__traits(compiles, { 10 __traits(getMember, target, prop) = __traits(getMember, source, prop); 11 })) 12 { 13 __traits(getMember, target, prop) = __traits(getMember, source, prop); 14 } 15 } 16 } 17 18 /// 19 unittest 20 { 21 struct A 22 { 23 int x; 24 int y; 25 } 26 struct B 27 { 28 int x; 29 float z; 30 } 31 32 A a = { x: 10, y: 20 }; 33 B b = { x: 1, z: 1.0f }; 34 assign(a, b); 35 36 assert(a.x == 1); 37 } 38 39 unittest 40 { 41 struct A 42 { 43 float x; 44 int y; 45 } 46 struct B 47 { 48 int x; 49 float y; 50 } 51 52 A a = { x: 10.0f, y: 20 }; 53 B b = { x: 1, y: 1.0f }; 54 assign(a, b); 55 56 assert(a.x == 1.0f); 57 assert(a.y == 20); // non compatible types 58 }