Skip to content

slice::reverse

slice methods · Collections

Level: reference · for working programmers

One line: Reverse the order of the elements, in place.

pub const fn reverse(&mut self)

Stable since 1.0.0; const since 1.90.0.

In place, so it needs &mut, and it returns ()println!("{:?}", v.reverse()) prints () and reverses the vector behind you, same as sort. For a reversed copy leave the slice alone and iterate: v.iter().rev().

sort() then reverse() is a descending sort, and it is fine; sort_by(|a, b| b.cmp(a)) does it in one pass.

It reverses elements. On the bytes of a string that is not a reversed string — a multi-byte character comes out backwards and the result is not UTF-8 — so a reversed &str is s.chars().rev().collect::<String>(), which reverses characters.

Example

slice_reverse.rs in full — pasted here by tools/run_examples.py from the file CI compiles and runs.

fn main() {
    let mut v = vec![1, 2, 3];
    v.reverse();
    println!("{v:?}");

    // For a reversed copy, iterate instead; v is untouched.
    let copy: Vec<i32> = v.iter().rev().copied().collect();
    println!("{copy:?} {v:?}");

    // Descending sort: sort, then reverse.
    let mut nums = vec![3, 1, 2];
    nums.sort();
    nums.reverse();
    println!("{nums:?}");

    // A sub-range reverses on its own.
    let mut part = vec![1, 2, 3, 4, 5];
    part[1..4].reverse();
    println!("{part:?}");

    // It returns (): binding or printing the call is the trap.
    let receipt = part.reverse();
    println!("{receipt:?} {part:?}");

    // Reversing a string is by chars, not by bytes.
    let back: String = "abc".chars().rev().collect();
    println!("{back}");
}

Verified output of slice_reverse.rs — regenerated by tools/run_examples.py, never hand-typed.

[3, 2, 1]
[1, 2, 3] [3, 2, 1]
[3, 2, 1]
[1, 4, 3, 2, 5]
() [5, 2, 3, 4, 1]
cba

See also

slice::reverse in the standard library ↗