Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I join a Vec<> of i32 numbers into a String? [duplicate]

Tags:

rust

I want to join a list of numbers into a String. I have the following code:

let ids: Vec<i32> = Vec::new();
ids.push(1);
ids.push(2);
ids.push(3);
ids.push(4);
let joined = ids.join(",");
print!("{}", joined);

However, I get the following compilation error:

error[E0599]: no method named `join` found for struct `std::vec::Vec<i32>` in the current scope
  --> src\data\words.rs:95:22
   |
95 |     let joined = ids.join(",");
   |                      ^^^^ method not found in `std::vec::Vec<i32>`
   |
   = note: the method `join` exists but the following trait bounds were not satisfied:
           `<[i32] as std::slice::Join<_>>::Output = _`

I'm a bit unclear as to what to do. I understand the implementation of traits, but whatever trait it's expecting, I would expect to be natively implemented for i32. I would expect joining integers into a string to be more trivial than this. Should I cast all of them to Strings first?

EDIT: It's not the same as the linked question, because here I am specifically asking about numbers not being directly "joinable", and the reason for the trait to not be implemented by the number type. I looked fairly hard for something in this direction and found nothing, which is why I asked this question.

Also, it's more likely that someone will search specifically for a question phrased like this instead of the more general "idiomatic printing of iterator values".

like image 824
Daniel Gray Avatar asked Apr 04 '20 17:04

Daniel Gray


People also ask

How do you attach a VEC to a string in Rust?

If you have a vector of strings, you can concatenate by using the concat() method. This method will expand the vector into a single string value. An example code is as shown: let arr = vec!

What does VEC mean in Rust?

A contiguous growable array type, written as Vec<T> , short for 'vector'.

How do you make an empty vector in Rust?

In Rust, there are several ways to initialize a vector. In order to initialize a vector via the new() method call, we use the double colon operator: let mut vec = Vec::new(); This call constructs a new, empty Vec<T> .


1 Answers

I would do

let ids = vec!(1,2,3,4);
let joined: String = ids.iter().map( |&id| id.to_string() + ",").collect(); 
print!("{}", joined);

Generally when you have a collection of one type in Rust, and want to turn it to another type, you call .iter().map(...) on it. The advantage of this method is you keep your ids as integers which is nice, have no mutable state, and don't need an extra library. Also if you want a more complex transformation than just a casting, this is a very good method. The disadvantage is you have a trailing comma in joined. playground link

like image 166
David Sullivan Avatar answered Sep 28 '22 08:09

David Sullivan