Skip to content

Instantly share code, notes, and snippets.

@mehmetsefabalik
Created July 11, 2021 14:30
Show Gist options
  • Save mehmetsefabalik/2f07df9bcc902d6149a80ad0ccfd5cde to your computer and use it in GitHub Desktop.
Save mehmetsefabalik/2f07df9bcc902d6149a80ad0ccfd5cde to your computer and use it in GitHub Desktop.
Sort Vector of Tuples in Rust
fn main() {
let mut v: Vec<(&str, i32)> = vec![("a", 2), ("b", 1), ("c", 3)];
v.sort_by(|a, b| a.1.cmp(&b.1)); // increasing order
v.sort_by(|a, b| b.1.cmp(&a.1)); // decreasing order
println!("{:?}", v);
}
@raviSussol
Copy link

Hi @mehmetsefabalik,
How do you sort tuples vector if contents inside tuple is being changed to some option struct? For example,

struct Car {price: f64}

let mut v: Vec<(&str, Option<Car>)> = vec![
    ("a", Some(Car {price: 3.2})),
    ("b", Some(Car {price: 2.2})),
    ("c", Some(Car {price: 23.2}))
];

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment