On 3/6/2014 9:38 PM, Edwin van Leeuwen wrote:

I guess what I am trying to do is allow code that looks like this:

v = add_to_vector( x, v );

while enforcing that v is never copied. I know there are other ways to
do this, i.e.
void add_to_vector( x, ref v );

but for me the earlier pattern is more explicit about what is happening,
while still being as efficient.


import std.stdio;

struct Foo {
    int x, y;
}

Foo add( Foo f, int val ) {
    writefln( "By val verision" );
    return Foo( f.x + val, f.y + val );
}

Foo add( ref Foo f, int val ) {
    writefln( "Ref version" );
    return Foo( f.x + val, f.y + val );
}

void main() {
    Foo f1 = Foo( 1, 2 );
    Foo f2 = add( f1, 1 ); // by ref version

    import std.algorithm : move;
    Foo f3 = add( f2.move, 4 ); // by val version, no copy

    // First is by ref, second is by val with no copy
    Foo f4 = f3.add( 2 ).add( 5 );
}

Reply via email to