Из документации:
«Оператор with - это способ упростить повторяющиеся ссылки на один и тот же объект.»
Когда я увидел это упомянутое в документации, я подумал, что это будет полезно для математики, где синтаксис должен выглядеть знакомым, а код повторно обращается к одному и тому же объекту.
struct Values
{
double x,y,vx,vy,ax,ay,dt;
int i;
void set_i( int i )
{
this.i = i;
}
alias int NestedType;
};
void main()
{
//Setup:
Values vals;
vals.i = 10;
//Usage of with:
with(vals)
// with(otherVals) // <<-- Easy to switch the 'with' scope to deal with a different instance:
{
// Imports all the member symbols of the struct or class into present scope
// without needing to refer every time to vals:
assert( i == 10 );
// Good for "repeated references to the same object": Helpful for maths where the syntax needs to look familiar, and repeatedly accesses the same object:
x += vx*dt;
y += vy*dt;
vx += ax*dt;
vy += ay*dt;
// Call the member functions too:
set_i(42);
// ... and get nested types/enums etc etc
NestedType ex;
}
// Results are persist (i.e.: all above writes were by reference:
assert( vals.i == 42 );
//Equivalent usage without 'with':
{
Values* vp = &vals; // get a reference to vals
assert( vp.i == 42 );
// This looks a lot Uglier than the previous one:
vp.x += vp.vx*vp.dt;
vp.y += vp.vy*vp.dt;
vp.vx += vp.ax*vp.dt;
vp.vy += vp.ay*vp.dt;
vp.set_i(56);
Values.NestedType ex;
}
assert( vals.i == 56 );
}