[rust-dev] &self/&mut self in traits considered harmful(?)

Tommi rusty.gates at icloud.com
Fri Jun 13 03:39:51 PDT 2014


That was assuming `Vector` implements `Clone`. For example:

#[deriving(Clone)]
struct Vector {
    coordinates: Vec<int>
}

On 2014-06-13, at 13:14, Tommi <rusty.gates at icloud.com> wrote:

> Taking an argument by "stable value" (as `self` above) means that any (clonable) variable passed in as that argument is implicitly cloned before it's passed in if the variable is potentially used after been passed in. For example:
> 
> impl Mul<int, Vector> for Vector {
>     fn mul(stable self, rhs: &int) -> Vector {
>         for c in self.coordinates.mut_iter() {
>             *c *= *rhs;
>         }
>         self
>     }
> }
> 
> fn testing() {
>     let mut v = Vector { coordinates: vec!(1, 2, 3) };
>     v * 1; // Cloned due to not last use
>     v * 1; // Not cloned due to last use before assignment
>     v = Vector { coordinates: vec!(2, 4, 6) };
>     v * 1; // Cloned due to not last use
>     v = v * 1; // Not cloned due to last use before assignment
>     v * 1; // Not cloned due to last use
> }

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.mozilla.org/pipermail/rust-dev/attachments/20140613/a42f3f61/attachment.html>


More information about the Rust-dev mailing list