nawat
nawat

Reputation: 41

How to sort immutable slice in Rust?

Suppose that I have the following code snippet:

fn foo(xs: &[i32]) {
    xs.sort(); // doesn't work since not mut
    // computation on xs
}

This function takes in an unsorted immutable slice but I need it to be sorted for computations later on in the function. I also cannot change the function signature. Is there a way to sort xs out of place or a way to convert xs into a mutable slice?

I've tried cloning and mapping but it seems that the problem is with the type of xs.

Upvotes: 3

Views: 4175

Answers (1)

hkBst
hkBst

Reputation: 3360

Since the data is immutable, you have to make a mutable copy of it first. You do not statically know the size of the slice parameter, so you need to use a Vec (instead of an array) to copy into. Then you can sort that Vec and use it normally in the rest of your function:

fn foo(xs: &[i32]) {
    let mut xs = xs.to_vec();
    xs.sort();
    // computation on xs
}

Upvotes: 9

Related Questions