On 07/05/2012 05:35 PM, Alexander Stavonin wrote:
Can someone give a good enough explanation of 'copy' keyword usage? I
can't find it neither in documentation nor tutorial.

In Rust we are trying to make it so that it isn't possible to accidentally make expensive or logically incorrect copies of values, so there are some types that may not be copied implicitly. When you try to write code that requires a copy of one of these types then rustc makes you insert the word 'copy' to prove you know what you are doing.

There are two reasons a type may not be implicitly copyable:

1) The type has mutable fields. Stateful types are usually considered to have 'identity' and you don't typically want to be making incidental copies of these because it is easy to end up thinking you are working with two variables representing the same thing, when you are actually working with two different things with different states.

2) Types that require allocation to create and are uniquely owned are expensive to copy because they must allocate new memory. This includes unique boxes and unique closures. Local boxes and closures do not have this property because copying them just shares a pointer to the same allocation.

As an example, strings are unique types (currently - this will change)
so they are not implicitly copyable.

   let x = "hello";
   let y = x; // copying x
   let z = x; // moving x (last use)

If you write this now rustc will issue a warning about `y = x` because in order to assign x to y it needs to make a copy. In the future this
will just be an error. To make it go away you write `let y = copy x`.

(The final line that assigns x to z illustrates the 'last use' rule, where rust will convert the last use of most variables into a move, eliminating the need for many explicit copies. That line is required for this example because otherwise `let y = x` gets converted to a move automatically. Last use behavior will probably
go away in the future because it is too clever for humans to reason about).


_______________________________________________
Rust-dev mailing list
Rust-dev@mozilla.org
https://mail.mozilla.org/listinfo/rust-dev

Reply via email to