Sometimes there are many ways for a program to phrase a message to its users, where the message involves a numeric figure. For instance, "{} minutes remaining." or "You need to finish in less than {} minutes.". None of them are mere prefixes, not all are mere suffixes, and many are both prefixes and suffixes. In a dynamic language, this would've seemed the logical task for string formatting.
For I/O 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 both be (a) tedious to author (w.r.t. typing out format!(/*...*/, x) each time) and (b) wasteful of memory+clock-cycles (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.)
Aucun commentaire:
Enregistrer un commentaire