rust-book/twelve_days_of_christmas/src/main.rs

59 lines
1.5 KiB
Rust

const ORDINALS: [&str; 12] = [
"first",
"second",
"third",
"fourth",
"fifth",
"sixth",
"seventh",
"eighth",
"ninth",
"tenth",
"eleventh",
"twelfth",
];
const GIFTS: [&str; 12] = [
"Twelve drummers drumming",
"Eleven pipers piping",
"Ten lords a-leaping",
"Nine ladies dancing",
"Eight maids a-milking",
"Seven swans a-swimming",
"Six geese a-laying",
"Five golden rings",
"Four calling birds",
"Three french hens",
"Two turtle doves",
"and a partridge in a pear tree.",
];
fn format_verse(day: &str, gifts: &str) -> String {
format!("On the {} day of Christmas, my true love gave to me: \n{}\n", day, gifts)
}
fn main() {
for n in 0..12 {
let verse: String = match n {
0 => format_verse("first", "A partridge in a pear tree."),
_ => {
// The highest index is 11, and we want
// the highest index to start, so we can
// easily have the cumulative list each verse.
let gift_index = 11 - n;
// Get the slice of the array of gifts, from
// the index to the end of the array
let gifts = &GIFTS[gift_index..]
.to_vec() // So we have the join method that returns a string
.join(",\n");
format_verse(ORDINALS[n], gifts)
}
};
// For some reason, the println! macro only takes string literals
println!("{}", verse);
}
}