It seems simple enough. I have a vector of i32 values. I just want to make that into a string. in my example, stuff_str would be “55208”;
Here’s the code:
let stuff = vec![5, 5, 2, 0, 8];
let stuff_str: String = stuff.into_iter().collect::<i32>().to_string();
But I get compile error:
|
52 | let stuff_str: String = stuff.into_iter().collect::<i32>().to_string();
| ^^^^^^^ a collection of type `i32` cannot be built from an iterator over elements of type `{integer}`
|
I tried a few different things but am having a block here.
You’ll want to apply to_string to each item, rather than to the collection like you are doing now.
If I’m not mistaken (on mobile, so can’t really check): .map(to-string), which should result in a Vec<String>
After that, there should be an applicable join method to turn your Vec<String> into a String.
So are you trying to make a Vec<String> of the individual numbers? Or are you trying to get a string representation of the entire vec?
It sounds like you want the latter, in which case you can do let stuff_str = format!("{:?}", stuff); to get a String of the Vec's Debug representation. The formatting wouldn’t exactly match what you’re after though.
If I understood your intent correctly, then to_string and format! variants suggested in this thread are slightly incorrect, as they do not check if number falls into 0…9 range. Plus they are somewhat ineffective, as they allocate a new string for each number. Alternative solution which handles those issues can look like this:
let stuff_str: String = stuff.into_iter().map(|b| {
assert!(b >=0 && b <= 9);
(b as u8 + 48) as char
}).collect();
Here I use the fact that digits in ASCII (and as a consequence in UTF-8) are ordered and ‘0’ is 48 if represented as a byte.