We can make use of the sort() method to sort a Vector in Rust Language.
Let's take a look at a few examples:
Example 1: Sort a vector of Numbers
fn main() {
let mut numbers = vec![15, 22, 37, 13, 91, 32, 42];
numbers.sort();
println!("Sorted numbers vector: {:?}", numbers);
}
Output:
Sorted numbers vector: [13, 15, 22, 32, 37, 42, 91]
Example 2: Sort a vector of Strings
fn main() {
let mut cities = vec!["Chicago", "Mumbai", "Paris", "Tokyo", "Sydney"];
cities.sort();
println!("Sorted cities Vector: {:?}", cities);
}
Output:
Sorted cities Vector: ["Chicago", "Mumbai", "Paris", "Sydney", "Tokyo"]
Facing issues? Have Questions? Post them here! I am happy to answer!
Author Info:
Rakesh (He/Him) has over 14+ years of experience in Web and Application development. He is the author of insightful How-To articles for Code2care.
Follow him on: X
You can also reach out to him via e-mail: rakesh@code2care.org
More Posts related to Rust,
- Rust: Cargo Init vs Cargo New Command
- Rust: Write and Run Hello World! Program Example
- How to Split a String using Rust Language
- How to Sort a Vector in Rust with Examples
- Fix: error: could not find `Cargo.toml` in Users or any parent directory
- How to uninstall Rust Language from Mac/Linux/Ubuntu
- How to update Cargo (Rust Lang)
- Fix: rust-analyzer failed to discover workspace [Visual Studio Code]
- How to install Rust using rustup on macOS/Linux/Ubuntu
- Cargo Watch: To Recompile Rust Project Automatically
- Difference between rustc and cargo build commands
- How to Split a String by Space in Rust
- How to know Rust is Installed on Mac?
- Rust: zsh: no such file or directory: ./main
- How to update Rust on Mac/Linux
- List of Rust Cargo Commands
- How to find version of Cargo in Rust
- Fix: error: mismatched closing delimiter } [Rust]
More Posts:
- How to upgrade PowerShell on Mac - Powershell
- iPhone network says SOS Only on Status Bar - iOS
- How to show line numbers in Nano on Mac - MacOS
- You can now Transfer Facebook Posts to Google Photos, Docs, Checkout how! - News
- Deploy SharePoint wsp solution package using PowerShell - SharePoint
- Fix - npm start: sh: index.js: command not found - JavaScript
- Your JBoss Application Server 7 is running However you have not yet added any users to be able to access the admin console - Java
- Generate Facebook Android SDK keyhash using java code - Android