Created
March 15, 2018 22:21
-
-
Save ejpcmac/f40bc5c141ecf13144805122dfec2e98 to your computer and use it in GitHub Desktop.
Procedural vs functional Rust for passphrase generation
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
// 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