Skip to content

Instantly share code, notes, and snippets.

@ejpcmac
Created March 15, 2018 22:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ejpcmac/f40bc5c141ecf13144805122dfec2e98 to your computer and use it in GitHub Desktop.
Save ejpcmac/f40bc5c141ecf13144805122dfec2e98 to your computer and use it in GitHub Desktop.
Procedural vs functional Rust for passphrase generation
// Let’s say we have a word list.
let word_list: Vec<String> = ...;
// We want to generate a random passphrase using words from the list.
// Let’s see how to do this with equal performance in two different styles:
// procedural and functional Rust.
// In both cases we need a random generator.
let mut rng = rand::thread_rng();
// The procedural way.
let mut passphrase = String::new();
for _ in 0..config.words {
let word = rng.choose(&word_list).unwrap();
passphrase.push_str(word);
passphrase.push_str(" ");
}
// The functional way.
let mut passphrase = (0..config.words).fold(String::new(), |s, _| {
s + rng.choose(&word_list).unwrap() + " "
});
// Pop the trailing space.
passphrase.pop();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment