Sometimes there are many ways for a program to phrase a message containing a dynamic value to its users. For instance:
- "{} minutes remaining."
- "You need to finish in less than {} minutes."
Not all of the messages contain the value as a mere prefix or suffix. In a dynamic language, this would've seemed the logical task for string formatting.
For media where repetitiveness is undesirable (e.g. Slack channels) there are so many different phrasings that producing each final String
to output using something like:
pub fn h(x: usize) -> String {
rand::sample(rand::thread_rng(), vec![
format!("{} minutes remain.", x),
format!("Hurry up; only {} minutes left to finish.", x),
format!("Haste advisable; time ends in {}.", x),
/* (insert many more elements here) */
], 1).first().unwrap_or(format!("{}", x))
}
Would be:
- Tedious to author, with respect to typing out
format!(/*...*/, x)
each time. - Wasteful of memory+clock-cycles as every single possibility is fully-generated before one is selected, discarding the others.
Is there any way to avoid these shortcomings?
Were it not for the compile-time evaluation of format strings, a function returning a randomly-selected &'static str
(from a static slice) to pass into format!
, would have been the preferred solution.