Is there way to unfold/unpack slices?

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?

  • 3

    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 a Display implementation is better, because often you will take the returned string and format it into another string. Using Display 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 a String, you can just call .to_string() on the Display value, and it winds up doing the same thing as format! anyway.

    – 

  • Here’s an example of what I mean. With this you can call .to_string() on a PhoneNumber if you actually want a String, but if you’re writing the phone number into a larger string, you can format the PhoneNumber directly, which avoids creating a temporary String 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.

    – 




Leave a Comment