我想将数字列表连接到字符串中。我有以下代码:
let ids: Vec<i32> = Vec::new();
ids.push(1);
ids.push(2);
ids.push(3);
ids.push(4);
let joined = ids.join(",");
print!("{}", joined);
Run Code Online (Sandbox Code Playgroud)
但是,我收到以下编译错误:
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 = _`
Run Code Online (Sandbox Code Playgroud)
我有点不清楚该怎么办。我了解特征的实现,但无论它期望什么特征,我都希望能够在本机实现i32. 我希望将整数连接到字符串中比这更简单。我应该把它们全部投给Strings 吗?
编辑:这与链接的问题不同,因为在这里我特别询问数字不是直接的“join能够”,以及该特征不能由数字类型实现的原因。我在这个方向上相当努力地寻找一些东西,但一无所获,这就是我问这个问题的原因。
此外,更有可能有人会专门搜索这样的问题,而不是更一般的“迭代器值的惯用打印”。
如果您不想显式转换为字符串,那么您可以使用Itertools::join方法(尽管这是一个外部板条箱)
相关代码:
use itertools::Itertools;
let mut ids: Vec<i32> = ...;
let joined = Itertools::join(&mut ids.iter(), ",");
print!("{}", joined);
Run Code Online (Sandbox Code Playgroud)
Frxstrem建议:
let joined = ids.iter().join(".");
Run Code Online (Sandbox Code Playgroud)
我会做
let ids = vec!(1,2,3,4);
let joined: String = ids.iter().map( |&id| id.to_string() + ",").collect();
print!("{}", joined);
Run Code Online (Sandbox Code Playgroud)
一般来说,当你在 Rust 中有一个类型的集合,并且想要将其转换为另一种类型时,你可以调用.iter().map(...)它。这种方法的优点是你可以将 id 保留为整数,这很好,没有可变状态,并且不需要额外的库。另外,如果您想要一个比铸造更复杂的转换,这是一个非常好的方法。缺点是后面有一个逗号joined。游乐场链接
使用该[T]::join()方法需要[T]实现该Join特征。该Join特征仅在实现(like或) 或(like或)[T]时实现。换句话说,您只能连接字符串向量或切片/向量向量。TBorrow<str>String&strBorrow<[U]>&[U]Vec<U>
一般来说,Rust 要求您对类型转换非常明确,因此在许多情况下您不应该期望该语言自动将整数转换为字符串。
要解决您的问题,您需要在将整数推入向量之前将它们显式转换为字符串:
let mut ids: Vec<String> = Vec::new();
ids.push(1.to_string());
ids.push(2.to_string());
ids.push(3.to_string());
ids.push(4.to_string());
let joined = ids.join(",");
print!("{}", joined);
Run Code Online (Sandbox Code Playgroud)