Skip to content

Instantly share code, notes, and snippets.

@jamland
Last active August 23, 2022 18:56
Show Gist options
  • Save jamland/5c3130e7bc5ee1f9c986822f0255e8e3 to your computer and use it in GitHub Desktop.
Save jamland/5c3130e7bc5ee1f9c986822f0255e8e3 to your computer and use it in GitHub Desktop.
Struct list manipulations in Rust
// 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);
}
@jamland
Copy link
Author

jamland commented Aug 23, 2022

output ===>

[src/main.rs:69] mapped = [
    "Bob πŸ™ŽπŸ»\u{200d}β™‚\u{fe0f}",
    "Carol 🐱",
]

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