Last active
August 23, 2022 18:56
-
-
Save jamland/5c3130e7bc5ee1f9c986822f0255e8e3 to your computer and use it in GitHub Desktop.
Struct list manipulations in Rust
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// this is Rust example of common manipulations over list in functional way | |
// similar to how it is usually done with JavaScript | |
// PartialEq, Eq, PartialOrd, Ord are needed to do sort later | |
#[derive(Debug, PartialEq, Eq, PartialOrd, Ord)] | |
enum Gender { | |
Male, | |
Female, | |
Other, | |
} | |
// PartialEq, Eq, PartialOrd, Ord are needed to do sort later | |
#[derive(Debug, PartialEq, Eq, PartialOrd, Ord)] | |
struct Person { | |
name: String, | |
email: String, | |
active: bool, | |
gender: Gender, | |
} | |
fn main() { | |
let alice = Person { | |
name: String::from("Alice"), | |
email: String::from("alice@example.com"), | |
active: false, | |
gender: Gender::Female, | |
}; | |
let bob = Person { | |
name: String::from("Bob"), | |
email: String::from("bob@example.com"), | |
active: true, | |
gender: Gender::Male, | |
}; | |
let carol = Person { | |
name: String::from("Carol"), | |
email: String::from("carol@example.com"), | |
active: true, | |
gender: Gender::Other, | |
}; | |
let mut people = vec![alice, carol, bob]; | |
// sort list by first field (name, default sorting by first field) | |
// filter only active users | |
// add emoji ππ½ββοΈ, ππ»ββοΈ, π± to name based on gender enum | |
// vec::sort sorts mutable list | |
people.sort(); | |
// create iterator, filter, map, and collect iterator back into collection | |
let mapped: Vec<String> = people | |
.into_iter() | |
.filter(|x| x.active) | |
.map(|x| { | |
let emoji = match x.gender { | |
Gender::Male => "ππ»ββοΈ", | |
Gender::Female => "ππ½ββοΈ", | |
Gender::Other => "π±", | |
}; | |
let name = format!("{} {}", x.name.to_owned(), emoji); | |
name | |
}) | |
.collect(); | |
dbg!(mapped); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
output ===>