arraysrusttype-conversion

How to convert an array to an array in rust?


I would like to convert an array of one type [T; N] into an array of another type [U; N] where U: From<T>. Is there any language syntax or std functionality that allows this without a heap allocation? If not, why not? Is there something about the language design that makes doing this difficult to implement?


Solution

  • Use .map():

    let strings: [String; 3] = [1, 2, 3].map(|num| num.to_string());
    

    This is different from the Iterator method of the same name; this method is directly on arrays and converts from [T; N] to [U; N] using the given functor.