---
title: "Write a Rust function to reverse the order of elements in a vector."  
description: "Write a Rust function to reverse the order of elements in a vector."  
author: "Utpal Vishwas"  
published: 2023-06-20  
updated: 2023-06-24  
canonical: https://www.mindstick.com/forum/158799/write-a-rust-function-to-reverse-the-order-of-elements-in-a-vector  
category: "rust"  
tags: ["programs", "rust"]  
reading_time: 2 minutes  

---

# Write a Rust function to reverse the order of elements in a vector.

Write a [Rust](https://www.mindstick.com/forum/160170/explain-rust-s-ownership-borrowing-and-lifetimes-system) [function to reverse](https://www.mindstick.com/forum/158747/implement-a-function-to-reverse-the-order-of-words-in-a-given-sentence) the [order](https://www.mindstick.com/articles/12276/how-timely-order-deliveries-can-improve-customer-experience) of [elements](https://www.mindstick.com/forum/1440/wpf-button-with-multiple-text-elements) in a vector.

## Replies

### Reply by Aryan Kumar

Sure, here is a Rust [function](https://www.mindstick.com/articles/13001/multi-statement-table-valued-user-defined-function-in-sql-server) to [reverse](https://www.mindstick.com/blog/63740/what-are-the-most-effective-and-safest-thanks-to-reverse-erectile-dysfunction) the order of elements in a vector:

Rust

```plaintext
fn reverse_vector(vector: &mut Vec<i32>) {
  // Initialize two iterators, one at the beginning of the vector and one at the end.
  let mut i = 0;
  let mut j = vector.len() - 1;

  // Loop while the iterators haven't crossed.
  while i < j {
    // Swap the elements at the two iterators.
    let temp = vector[i];
    vector[i] = vector[j];
    vector[j] = temp;

    // Increment i.
    i += 1;

    // Decrement j.
    j -= 1;
  }
}

fn main() {
  // Create a vector.
  let mut vector = vec![1, 2, 3, 4, 5];

  // Reverse the order of the elements in the vector.
  reverse_vector(&mut vector);

  // Print the vector.
  for i in 0..vector.len() {
    println!("{}", vector[i]);
  }
}
```

This function first initializes two iterators, one at the beginning of the vector and one at the end. The function then loops while the iterators haven't crossed. In each iteration of the loop, the function swaps the elements at the two iterators. The function then increments i and decrements j. Finally, the function prints the vector.

To run this program, you can save it as a `.rs` file and then compile and run it using the following commands:

Code snippet

```plaintext
rustc reverse_vector.rs
./reverse_vector
```

This will print the following output:

Code snippet

```plaintext
5
4
3
2
1
```

This indicates that the order of the elements in the vector has been reversed.


---

Original Source: https://www.mindstick.com/forum/158799/write-a-rust-function-to-reverse-the-order-of-elements-in-a-vector

Copyright © MindStick Software Pvt. Ltd. This Markdown version is provided for developers, AI systems, and offline reading.
