What does the c keyword do in D 2.0?

There is a keyword in D 2.0 with, but I'm not sure what it does, or how to use it. My search for documentation was fruitless. Does anyone know what keyword usage is with? (Does this look like a C # instruction using? Or as a Visual Basic clause with?)

+3
source share
3 answers

It's right here: With an expression

The with statement is a way to simplify duplicate references to the same object.

It is used as follows:

with (expression)
{
  usage();
  writef("%s, %s", access, member);
}
+7
source

You can use the with statement to create anonymous objects if you need it:

class Foo { int x; }
void main()
{
    with (new Foo)
    {
        x = 5;
    }
}

with, Scintilla.

+6

: "" - ".

, , , , .

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 );

}
+1
source

Source: https://habr.com/ru/post/1793726/


All Articles