rust - 如何将 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
能够”,以及该特征不能由数字类型实现的原因。我在这个方向上相当努力地寻找某些东西,但什么也没找到,这就是我问这个问题的原因。
此外,更有可能有人会专门搜索这样的问题,而不是更一般的“迭代器值的惯用打印”。
解决方案
如果您不想显式转换为字符串,则可以使用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(".");
推荐阅读
- anaconda - 为什么路径包含在 conda 提示符中以及如何缩短它
- python - 将 Blob 数据插入 Sqlite3 (GeoPackage)
- nginx - 为什么我在 nginx 反向代理上得到 404?
- kotlin - 处理来自服务的空正文响应
- java - 如何用鼠标单击 LibGdx 创建对象
- python - 如何在 fasta 文件中并行化计算,其中每个处理器采用一个序列
- opencart - 如何在 OpenCart 扩展中转换安装/卸载方法
- pandoc - 当 biblio 文件仅在 YAML 元数据中时,pandoc 不会生成参考书目
- c# - 如何将 WPF 视图注入从 VSTO 插件 Prism 7 调用的窗口中
- swift - 我可以从该协议中获取符合协议的类型的名称吗?