Skip to navigation
Convert a Vec of i64 into a Vec of Strings in rust
10.10.25
``` let vs: Vec
= v.into_iter().map(|n| n.to_string()).collect(); ``` To convert a Vec
into a Vec
in Rust, you can iterate over the Vec
, convert each i64 element to a String, and then collect these Strings into a new Vec
. According to www.iAsk.Ai - Ask AI: The most idiomatic and efficient way to achieve this in Rust is by using the into_iter(), map(), and collect() methods. This approach leverages Rust's iterator adaptors for concise and performant transformations [1] [2]. Here's a step-by-step breakdown: Start with your Vec
: Let's assume you have a vector named my_i64_vec of type Vec
. let my_i64_vec: Vec
= vec![1, 2, 3, 4, 5]; Convert the Vec into an iterator: The into_iter() method consumes the vector and produces an iterator that yields each element by value. This is generally preferred when you no longer need the original vector [3]. my_i64_vec.into_iter() Map each element to a String: The map() method applies a closure to each element produced by the iterator. Inside this closure, you'll convert each i64 to a String. The to_string() method, available on all types that implement the Display trait (which i64 does), is perfect for this [4] [5]. .map(|n| n.to_string()) This step transforms an iterator of i64 into an iterator of String. Collect the results into a new Vec
: The collect() method consumes the iterator and gathers the results into a specified collection type. In this case, we want a Vec
[3]. .collect::
>(); The type annotation ::
> is often necessary for collect() to infer the desired output type. Combining these steps, the complete solution is: let my_i64_vec: Vec
= vec![1, 2, 3, 4, 5]; **let my_string_vec: Vec
= my_i64_vec.into_iter().map(|n| n.to_string()).collect();** // my_string_vec will now be Vec
= ["1", "2", "3", "4", "5"] This method is efficient because Rust's compiler is highly optimized for iterator chains, often inlining operations and avoiding intermediate allocations where possible [2]. This pattern is also widely used for type conversions on vectors in Rust, such as converting Vec
to Vec
using n as _ within the map closure [6]. For more complex scenarios where you might have a custom type like CourseName that wraps a String, you would implement the Display trait for your custom type. This allows to_string() to work correctly on instances of your custom type, enabling a similar map().collect() pattern Tags: vecconvert, vecrust, vec2string
https://doc.rust-lang.org/rust-by-example/
Reply
Anonymous
Information Epoch 1760439554
Make each program do one thing well.
Home
Notebook
Contact us