In order to learn Rust I'm going through The Rust Book and did the implemented a program for the following exercise:
Print the lyrics to the Christmas carol “The Twelve Days of Christmas,” taking advantage of the repetition in the song.
I have decided to use lookup tables for the repeating lines of the song and ordinals because I believe those to be good for performance.
I'd appreciate any comments on my code, especially any suggestions on how to avoid the recurring magic number 12
.
type Day = u8;
const LYRICS: [&str; 12] = [
"a partridge in a pear tree",
"two turtle doves",
"three French hens",
"four calling birds",
"five gold rings",
"six geese a laying",
"seven swans a swimming",
"eight maids a milking",
"nine ladies dancing",
"ten lords a leaping",
"eleven pipers piping",
"twelve drummers drumming",
];
const ORDINALS: [&str; 12] = [
"first",
"second",
"third",
"fourth",
"fifth",
"sixth",
"seventh",
"eigth",
"ninth",
"tenth",
"eleventh",
"twelfth",
];
fn main() {
for day in 0..12 {
if day != 0 {
println!();
}
print_first_line(day);
print_lyrics(day);
}
}
fn print_first_line(day: Day) {
println!(
"On the {} day of Christmas my true love gave to me",
ORDINALS[day as usize],
)
}
fn print_lyrics(day: Day) {
for line in (0..=day).rev() {
if line == 0 && day != 0 {
println!("And {}", LYRICS[line as usize]);
} else {
println!("{}", capitalize(LYRICS[line as usize]));
}
}
}
fn capitalize(text: &str) -> String {
let mut chars = text.chars();
let mut new_text = String::with_capacity(text.len());
if let Some(c) = chars.next() {
new_text.extend(c.to_uppercase());
new_text.extend(chars);
}
new_text
}