rustownershipborrowing

Can I somehow modify a '&' array?


So basically I have this:

let mut sortedNumbers = numbers.clone();
    
sortedNumbers.sort_by(|a, b| b.rational.cmp(&a.rational));

Where numbers is a &[..]

I want to somehow sort the sortedNumbers vector, but the reference is not mutable. Any ideas?


Solution

  • If numbers is a &[T], then numbers.clone() is also a &[T], referring to the same array. What you want is numbers.to_vec() or numbers.to_owned(), which give you a Vec<T>, which you can then modify.