0

I'm new to Rust and I'm trying to get Vec<i32> element in swap() function and change it:

use std::ops::Index;
fn main() {
    let mut vec = Vec::new();
    for i in 0..10 {
        vec.push(i);
        print!("{} ", i);
    }
    println!(" <- Before sort");
    bubble_sort(&mut vec);
    for i in &vec {
        print!("{} ", i);
    }
    println!(" <- After sort");
}

fn bubble_sort(vec: &mut Vec<i32>) {
    for j in 0..(vec.len() - 1) {
        for i in 0..(vec.len() - j - 1) {
            if vec[i] < vec[i + 1] {
                swap(vec.index(i), vec.index(i + 1));
            }
        }
    }
}

fn swap<'l>(a: &'l mut i32, b: &'l mut i32) {
    let temp = *a;
    *a = *b;
    *b = temp;
}

Where I should set elements as mutable? If I trying do it in swap(vec.index(i), vec.index(i+1)); it says error: cannot borrow immutable borrowed content as mutable

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
Mhs
  • 1
  • [`slice::swap`](https://doc.rust-lang.org/std/primitive.slice.html#method.swap). – Shepmaster May 10 '17 at 22:00
  • Welcome to Stack Overflow! The code you have provided does **not** produce the error message you have provided, instead it says `types differ in mutability`. Please review how to create a [MCVE]; you will be expected to provide one for all questions where you ask "why isn't this code working?". – Shepmaster May 10 '17 at 22:03
  • https://gist.github.com/7245fbcac3450761e71469a5a7026f4d. See also [Why is it discouraged to accept a reference to a String (&String) or Vec (&Vec) as a function argument?](http://stackoverflow.com/q/40006219/155423). – Shepmaster May 10 '17 at 22:06
  • Thanks, I'll keep it in mind – Mhs May 10 '17 at 22:13

0 Answers0