0

I want to convert an array of [Decimal; 12] into [String; 12]

I use decimal module to store numbers, but I need to convert it into string for display

fn rows_to_string(arr: [Decimal; 12]) -> [String; 12] {
    arr.into_iter().map(|row| row.to_string()).collect()
}

But this give me error:

error: an array of type `[std::string::String; 12]` cannot be built directly from an iterator
label: try collecting into a `Vec<std::string::String>`, then using `.try_into()`
note: required by a bound in `collect`
label: try collecting into a `Vec<std::string::String>`, then using `.try_into()`

if I follow the error instruction and change the code above into:

fn rows_to_string(arr: [Decimal; 12]) -> [String; 12] {
    arr.into_iter()
        .map(|row| row.to_string())
        .collect::<Vec<String>>()
}

Now, the function returns a vector Vec<String>, instead of [String; 12]

DennyHiu
  • 4,861
  • 8
  • 48
  • 80
  • 2
    TLDR the duplicate: use `.collect::>().try_into()` (which is also what the compiler suggests). – Jmb Oct 14 '22 at 06:24
  • 1
    The iterator doesn't keep track of the length. So, collecting into a fixed size directly is (AFAIK) not possible (even though *you* know it will always have 12 elements). What you could do, is `.collect` into a `Vec`, then convert it back into an array using `.try_into().unwrap()` (safe to unwrap, you know it has the right size). – FZs Oct 14 '22 at 06:27
  • OK. it works now. thanks for @FZs to explain why – DennyHiu Oct 14 '22 at 06:30

0 Answers0