1

I have a Vec of UUID's. I want to add comma's between the UUID's and put the result in between two &str to create a String. This is what I have now:

pub fn select_ids(ids: Vec<Uuid>) -> String {
    let x: String = ids.into_iter().map(|id| {
        id.to_string() + ","
    }).collect();

    "(".to_owned() + &x + ")"
}

This is my test:

#[test]
fn t() {
    let uuid = Uuid::from_str("123e4567-e89b-12d3-a456-426655440000").unwrap();
    let x = select_ids(vec!(uuid, uuid.clone()));

    assert_eq!(x, "(123e4567-e89b-12d3-a456-426655440000,123e4567-e89b-12d3-a456-426655440000)");
}

It fails with the following:

Expected :(123e4567-e89b-12d3-a456-426655440000,123e4567-e89b-12d3-a456-426655440000)
Actual   :(123e4567-e89b-12d3-a456-426655440000,123e4567-e89b-12d3-a456-426655440000,)

Ofcourse I can cut off the last character, but that will fail if the list contains only 1 id. I am wondering if there is a build in option, like Java has (https://www.geeksforgeeks.org/java-8-streams-collectors-joining-method-with-examples/).

J. Doe
  • 12,159
  • 9
  • 60
  • 114
  • @justinas Just tried it, the join method isn't available on a Vec with UUID's properly :( – J. Doe Jan 30 '20 at 13:07
  • Well, you already `map()` them to strings, so I figured it would not be a problem to turn `Vec` to a `Vec` or similar. Do you need help with that? – justinas Jan 30 '20 at 13:33
  • @justinas this means they would have to `collect` into a temporary vector. @J. Doe the duplicate question has several answers. The `itertools` one would be the one to use here. – mcarton Jan 30 '20 at 14:57
  • [The duplicate applied to your question](https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=54bc52936ac3b1eaa6ae568ea75a63f6) – mcarton Jan 30 '20 at 15:00
  • @justinas No you were right, it is a duplicate and I just needed to create String Vec to make it work, thanks :) – J. Doe Jan 30 '20 at 16:55
  • @mcarton yes correct, my bad! – J. Doe Jan 30 '20 at 16:55

1 Answers1

1

You can use the join method from the itertools crate:

use itertools::join;
pub use uuid::Uuid;

pub fn select_ids(ids: Vec<Uuid>) -> String {
    "(".to_owned() + &join (ids, ",") + ")"
}

#[test]
fn t() {
    use std::str::FromStr;
    let uuid = Uuid::from_str("123e4567-e89b-12d3-a456-426655440000").unwrap();
    let x = select_ids(vec!(uuid, uuid.clone()));

    assert_eq!(x, "(123e4567-e89b-12d3-a456-426655440000,123e4567-e89b-12d3-a456-426655440000)");
}

Playground

Jmb
  • 18,893
  • 2
  • 28
  • 55