[rust-dev] Swapping elements in a vec

Graydon Hoare graydon at mozilla.com
Mon Feb 28 06:32:54 PST 2011

On 28/02/2011 12:41 AM, Peter Hull wrote:
> On Sun, Feb 27, 2011 at 10:19 PM, Graydon Hoare<graydon at mozilla.com>  wrote:
>> Yeah. You want vec[mutable int]. We'll probably wind up with a 'swap'
>> primitive at some point down the line when unique ownership and move
>> semantics are more thoroughly worked out.
> Thanks. To be more concrete, I was trying to write an iterator to
> generate all permutations of a vec:
> iter combinations[T](&vec[T] els) ->  vec[T]
> by
> 1. Making a mutable copy of els
> 2. Performing a sequence of swaps on my copy
> 3. 'put'ting a copy of each one
> I have a feeling maybe I don't understand mutability now - in code like
> let int i = 0;
> i = i + 1;
> Why doesn't i have to be mutable int?

At least at the moment, slots created with 'auto' and 'let' are mutable. 
Note that 'mutable' is only a 1-level-deep annotation: a mutable pointer 
to immutable data in the heap doesn't let you mutate the heap cells 
(say, the vec elements), only the pointer.

Curiously, by-value arguments are *not* mutable by default just now. So:

   fn foo(int x) {
       x += 1;

will not work, but:

   fn foo(int x) {
       let int y = x;
       y += 1;

will. I admit this is a strange distinction. It's possible we'll switch 
by-value arguments to implicitly-mutable as well, or go the other way 
and switch locals back to implicitly-immutable. We had locals as 
immutable, initially, but it "felt" a little too chatty when writing 
"essentially pure" code.

A word on *that* concept might be in order: at the moment our effect 
system considers a function "pure" if it mutates local variables. 
Depending on your opinion, this might be fudging the notion of "purity" 
or might be capturing its essence without getting too annoying. So long 
as mutation doesn't leave the local frame (i.e. no writes to the heap), 
we consider the function pure. Writing *through* a pointer to the heap 
gains you the 'impure' effect. I admit this is also a strange 
distinction; but it's somewhat coupled to the first, in that you're much 
more likely to *have* a bunch of mutable locals sitting around if we 
have 'let' mean 'let mutable'.

Getting the judgment right so that it captures what a programmer 
"usually" means by pure is a bit of a matter of taste. I'm quite willing 
to revisit this as experience and user-consensus develops.


More information about the Rust-dev mailing list