Rust 用逗号分隔Vec中的元素

Rust 用逗号分隔Vec中的元素,rust,Rust,我有一个Vec的UUID。我想在UUID之间添加逗号,并将结果放在两个&str之间,以创建一个字符串。这就是我现在拥有的: pub fn select_ids(ids: Vec<Uuid>) -> String { let x: String = ids.into_iter().map(|id| { id.to_string() + "," }).collect(); "(".to_owned() + &x + ")" } 它

我有一个
Vec
UUID
。我想在
UUID
之间添加逗号,并将结果放在两个
&str
之间,以创建一个
字符串。这就是我现在拥有的:

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

    "(".to_owned() + &x + ")"
}
它在以下情况下失败:

Expected :(123e4567-e89b-12d3-a456-426655440000,123e4567-e89b-12d3-a456-426655440000)
Actual   :(123e4567-e89b-12d3-a456-426655440000,123e4567-e89b-12d3-a456-426655440000,)
当然,我可以切掉最后一个字符,但如果列表中只包含1个id,则该操作将失败。我想知道是否有内置选项,如Java()。

您可以使用板条箱中的方法:

使用itertools::join;
pub-use-uuid::uuid;
发布fn选择_id(id:Vec)->字符串{
(“.to_owned()+&join(id,”,“+”)”
}
#[测试]
fn t(){
使用std::str::FromStr;
让uuid=uuid::from_str(“123e4567-e89b-12d3-a456-426655440000”).unwrap();
让x=选择_id(vec!(uuid,uuid.clone());
断言(x),(123e4567-e89b-12d3-a456-426655440000123E4567-e89b-12d3-a456-426655440000);
}

@justinas刚刚尝试过,join方法在具有UUID的Vec上不可用:(好吧,您已经
map())
将它们转换为字符串,因此我认为将
Vec
转换为
Vec
或类似的格式不会有问题。您需要帮助吗?@justinas这意味着他们必须将
收集成一个临时向量。@J.Doe重复的问题有几个答案。
itertools
就是这里要使用的答案@justinas不,你是对的,它是重复的,我只需要创建字符串Vec就可以了,谢谢:)
Expected :(123e4567-e89b-12d3-a456-426655440000,123e4567-e89b-12d3-a456-426655440000)
Actual   :(123e4567-e89b-12d3-a456-426655440000,123e4567-e89b-12d3-a456-426655440000,)
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)");
}