fn create_phone_number(numbers: &[u8; 10]) -> String {
format!("({}{}{}) {}{}{}-{}{}{}{}",
numbers[0], numbers[1], numbers[2],
numbers[3], numbers[4], numbers[5],
numbers[6], numbers[7], numbers[8],
numbers[9])
}
I’m writing this simple function to print out a phone number. Is there a way to write it shorter? In Python, I can just unpack it, so it would look like:
def create_phone_number(numbers):
return "({}{}{}) {}{}{}-{}{}{}{}".format(*numbers)
Is there a Rust equivalent?
Related: How can I spread a Vec<> into the arguments of format!()? and How do I use a macro to expand a tuple to its members as function arguments?
Side note, having a function return a
String
is often an anti-pattern in Rust. Writing a type with aDisplay
implementation is better, because often you will take the returned string and format it into another string. UsingDisplay
instead allows you to write the formatted value directly into the larger string where it will actually be used, and avoid a temporary allocation. And, if you actually do need aString
, you can just call.to_string()
on theDisplay
value, and it winds up doing the same thing asformat!
anyway.Here’s an example of what I mean. With this you can call
.to_string()
on aPhoneNumber
if you actually want aString
, but if you’re writing the phone number into a larger string, you can format thePhoneNumber
directly, which avoids creating a temporaryString
to hold the phone number. You could even modify this wrapper type so that the conversion from an array is fallible, failing if any of the digits is > 9.