[rust-dev] Optimizing pattern bindings to not copy anything at runtime

Niko Matsakis niko at alum.mit.edu
Wed Apr 23 19:09:10 PDT 2014

Ah, neat. I have been wanting to do this optimization for function
parameters for a long time, but I hadn't thought about it for other
kinds of bindings. Better yet, I think by-copy vs by-move is a red
herring. The optimization applies equally well in both scenarios.

That said, we do have to be a bit careful about mutability. Even just
considering by-move locals, for example, it is possible to have code
like the following:

    let mut x = something();
    let y = x;
    x = something_else();

If we just made y a pointer to x, we'd be in trouble.

Also, this statement isn't quite right:

> 2. The only things that can be moved out of in Rust are locals and rvalues.

You could e.g. move out of x.y.z. Moreover, I think we can support a
lot more. As part of #5016 I plan to allow you to continue the parts
of a struct that have not been moved out of. Better yet, if you
replace the moved out fields, you can go back to using the struct

    let foo = ...;
    let a = foo.a; // moves out of foo.a
    let b = foo.b; // moves out of foo.b
    foo.a = ...;
    foo.b = ...;

This all basically falls out of the analysis we're currently doing,
which tracks the precise deinitialized paths (e.g., foo.a, foo.b,
etc). We're just being overly restrictive for legacy reasons. I'm
working on a patch right now that should make it easy to change that.

At some point, I think we could even enable moves out of &mut, as long
as you replace the value before failure could occur. This would allow
tree-maps and the like to do rotations just as you do in C. But I
haven't tried to write formal rules for this yet.


More information about the Rust-dev mailing list