首页 > 解决方案 > 如何将 i32 数字的 Vec<> 加入字符串?

问题描述

我想将一个数字列表加入一个字符串。我有以下代码:

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

但是,我收到以下编译错误:

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 = _`

我有点不清楚该怎么做。我了解特征的实现,但无论它期望什么特征,我都希望在本地实现i32. 我希望将整数加入字符串比这更简单。我应该String先将它们全部转换为 s 吗?

编辑:这与链接的问题不同,因为在这里我特别询问数字不是直接“join能够”,以及该特征不能由数字类型实现的原因。我在这个方向上相当努力地寻找某些东西,但什么也没找到,这就是我问这个问题的原因。

此外,更有可能有人会专门搜索这样的问题,而不是更一般的“迭代器值的惯用打印”。

标签: rust

解决方案


如果您不想显式转换为字符串,则可以使用Itertools::join方法(虽然这是一个外部板条箱)

操场

相关代码:

use itertools::Itertools;

let mut ids: Vec<i32> = ...;
let joined = Itertools::join(&mut ids.iter(), ",");
print!("{}", joined);

Frxstrem 建议:

let joined = ids.iter().join(".");

推荐阅读