Create an options Struct

This commit is contained in:
runebaas 2019-10-27 23:03:43 +01:00
parent 23c0b242e9
commit b4df759781
No known key found for this signature in database
GPG key ID: 2677AF508D0300D6

View file

@ -2,6 +2,11 @@ use std::fs;
use rand::prelude::*;
use clap::{Arg, App};
struct Options {
filename: String,
length: usize
}
fn main() {
// specify app
let app = App::new("Fortune.rs")
@ -21,19 +26,15 @@ fn main() {
.help("Set the longest fortune length (in characters) considered to be 'short'. All fortunes longer than this are considered 'long'.")
.takes_value(true)
.value_name("length"));
let matches = app.get_matches();
// input variables
let filename = matches.value_of("file").unwrap().to_owned();
let max_length = matches.value_of("length").unwrap().parse::<usize>().expect("Length is not a valid number");
let options = parse_options(app);
// get fortunes
let fortunes = get_fortunes(filename);
let fortunes = get_fortunes(options.filename.clone());
// filter by max length
let filtered = fortunes
.into_iter()
.filter(|x| x.replace(" ", "").len() < max_length)
.filter(|x| x.replace(" ", "").len() < options.length)
.collect::<Vec<String>>();
// get a random one
@ -41,6 +42,16 @@ fn main() {
println!("{}", the_fortune);
}
fn parse_options(app: App) -> Options {
let matches = app.get_matches();
let options: Options = Options {
filename: matches.value_of("file").unwrap().to_owned(),
length: matches.value_of("length").unwrap().parse::<usize>().expect("Length is not a valid number")
};
return options;
}
fn get_fortunes(filename: String) -> Vec<String> {
let fortune_file = fs::read_to_string(filename).expect("Cannot read fortune file");
let fortunes: Vec<String> = fortune_file.split('%').map(ToOwned::to_owned).collect();